package com.basic.modules.ykf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.basic.common.exception.RRException;
import com.basic.common.utils.*;
import com.basic.modules.sys.entity.SysUserEntity;
import com.basic.modules.sys.service.SysUserService;
import com.basic.modules.ykf.entity.*;
import com.basic.modules.ykf.model.*;
import com.basic.modules.ykf.service.*;
import com.basic.modules.ykf.utils.ExcelCellWidthStyleStrategy;
import com.basic.modules.ykf.utils.ExcelStyleUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.basic.modules.ykf.dao.YkfAccountInputRecordDao;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;


@Service("ykfAccountInputRecordService")
public class YkfAccountInputRecordServiceImpl extends ServiceImpl<YkfAccountInputRecordDao, YkfAccountInputRecordEntity> implements YkfAccountInputRecordService {

    @Autowired
    private YkfNotCheckRecordService notCheckRecordService;

    @Autowired
    private YkfUserAttendanceRecordService attendanceRecordService;

    @Autowired
    private YkfCustomerSubAccountService subAccountService;

    @Lazy
    @Autowired
    private YkfSubAccountRecordService subAccountRecordService;

    @Autowired
    private YkfWorkOvertimeRecordService workOvertimeRecordService;

    @Autowired
    private YkfCustomPostCommissionService postCommissionService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private YkfCustomerSubAccountService ykfCustomerSubAccountService;

    @Autowired
    private YkfDictDetailService dictDetailService;

    @Lazy
    @Autowired
    private YkfCustomerShopService customerShopService;

    /**
     * 店铺每日绩效-分页
     */
    @Override
    public PageUtils dayPage(ParamsModel<YkfAccountInputRecordEntity> params) {
        if (ObjectUtil.isNotEmpty(params)
                && ObjectUtil.isNotEmpty(params.getCondition())
                && ObjectUtil.isNotEmpty(params.getCondition().getDateStart())
                && ObjectUtil.isNotEmpty(params.getCondition().getDateEnd())) {
            IPage<YkfAccountInputRecordEntity> page = new Query<YkfAccountInputRecordEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
//            List<Long> powerUserIds = sysUserService.getPowerUserIds();
//            params.getCondition().setCreateUserIds(powerUserIds);
            List<Long> powerSubAccountIds = sysUserService.getPowerSubAccountIds();

            if (ObjectUtil.isEmpty(powerSubAccountIds)) {
                return new PageUtils();
            } else {
                if (!powerSubAccountIds.contains(0L)) {
                    params.getCondition().setPowerSubAccountIds(powerSubAccountIds);
                }
            }
            List<Long> shopIds = sysUserService.getOneselfShopIds();
            if (ObjectUtil.isEmpty(shopIds)) {
                return new PageUtils();
            } else {
                if (!shopIds.contains(0L)) {
                    params.getCondition().setPowerShopIds(shopIds);
                }
            }
            IPage<YkfAccountInputRecordEntity> resultPage = baseMapper.dayPage(page, params.getCondition());
            if (ObjectUtil.isNotEmpty(resultPage) && ObjectUtil.isNotEmpty(resultPage.getRecords())) {
                for (YkfAccountInputRecordEntity record : resultPage.getRecords()) {
//                    if (ObjectUtil.isEmpty(record.getReceptionVolume()) || record.getReceptionVolume().compareTo(BigDecimal.ZERO) <= 0) {
//                        record.setResponseRate(BigDecimal.ZERO);
//                    } else {
//                        record.setResponseRate(record.getSumResponseRate().divide(record.getReceptionVolume(), 2, RoundingMode.HALF_UP));
//                    }
                    if (ObjectUtil.isNotEmpty(record.getReceptionVolume()) && ObjectUtil.isNotEmpty(record.getReceptionVolumeBase()) && record.getReceptionVolume().compareTo(record.getReceptionVolumeBase()) > 0) {
                        record.setReceptionVolumeDesc("合同约定为，" + record.getReceptionVolumeBase().toPlainString() + "此项绩效已超标");
                    }
                    if (ObjectUtil.isNotEmpty(record.getConversionRate()) && ObjectUtil.isNotEmpty(record.getConversionRateBase()) && record.getConversionRate().compareTo(record.getConversionRateBase()) > 0) {
                        record.setConversionRateDesc("合同约定为，" + record.getConversionRateBase().toPlainString() + "此项绩效未达标");
                    }
                    if (ObjectUtil.isNotEmpty(record.getResponseTime()) && ObjectUtil.isNotEmpty(record.getResponseTimeBase()) && record.getResponseTime().compareTo(record.getResponseTimeBase()) > 0) {
                        record.setResponseTimeDesc("合同约定为，" + record.getResponseTimeBase().toPlainString() + "此项绩效未达标");
                    }
                }
            }
            return new PageUtils(resultPage);
        } else {
            throw new RRException("参数缺失");
        }
    }

    /**
     * 店铺整体绩效-分页
     */
    @Override
    public PageUtils overallPage(ParamsModel<YkfAccountInputRecordEntity> params) {
        if (ObjectUtil.isNotEmpty(params)
                && ObjectUtil.isNotEmpty(params.getCondition())
                && ObjectUtil.isNotEmpty(params.getCondition().getDateStart())
                && ObjectUtil.isNotEmpty(params.getCondition().getDateEnd())) {
            IPage<YkfAccountInputRecordEntity> page = new Query<YkfAccountInputRecordEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
//            List<Long> powerUserIds = sysUserService.getPowerUserIds();
//            params.getCondition().setCreateUserIds(powerUserIds);
            List<Long> powerSubAccountIds = sysUserService.getPowerSubAccountIds();
            if (ObjectUtil.isEmpty(powerSubAccountIds)) {
                return new PageUtils();
            } else {
                if (!powerSubAccountIds.contains(0L)) {
                    params.getCondition().setPowerSubAccountIds(powerSubAccountIds);
                }
            }
            List<Long> shopIds = sysUserService.getOneselfShopIds();
            if (ObjectUtil.isEmpty(shopIds)) {
                return new PageUtils();
            } else {
                if (!shopIds.contains(0L)) {
                    params.getCondition().setPowerShopIds(shopIds);
                }
            }
            IPage<YkfAccountInputRecordEntity> resultPage;
//            long days = DateUtil.betweenDay(params.getCondition().getDateStart(), params.getCondition().getDateEnd(), true) + 1;
//            params.getCondition().setDays(new BigDecimal(days));
            if (ObjectUtil.isNotEmpty(params.getCondition().getShopId()) && ObjectUtil.isNotEmpty(params.getCondition().getDate())) {
                resultPage = baseMapper.overallPage3(page, params.getCondition());
            } else if (ObjectUtil.isNotEmpty(params.getCondition().getShopId())) {
                resultPage = baseMapper.overallPage2(page, params.getCondition());
            } else {
                resultPage = baseMapper.overallPage(page, params.getCondition());
            }
            if (ObjectUtil.isNotEmpty(resultPage) && ObjectUtil.isNotEmpty(resultPage.getRecords())) {
                for (YkfAccountInputRecordEntity record : resultPage.getRecords()) {
                    if (ObjectUtil.isEmpty(params.getCondition().getShopId()) && ObjectUtil.isEmpty(params.getCondition().getDate())) {
                        record.setReceptionVolume(record.getReceptionVolume().divide(record.getDays(), 0, RoundingMode.HALF_UP));
                    }

//                    record.setConversionRate(record.getConversionRate().divide(new BigDecimal(days), 0, RoundingMode.HALF_UP));
//                    record.setResponseTime(record.getResponseTime().divide(new BigDecimal(days), 0, RoundingMode.HALF_UP));
//                    record.setQARatio(record.getQARatio().divide(new BigDecimal(days), 0, RoundingMode.HALF_UP));
//                    record.setResponseRate(record.getResponseRate().divide(new BigDecimal(days), 0, RoundingMode.HALF_UP));
                    if (ObjectUtil.isNotEmpty(record.getConversionRate())) {
                        record.setConversionRate(record.getConversionRate().setScale(2, RoundingMode.HALF_UP));
                    }
                    if (ObjectUtil.isNotEmpty(record.getResponseTime())) {
                        record.setResponseTime(record.getResponseTime().setScale(2, RoundingMode.HALF_UP));
                    }
                    if (ObjectUtil.isNotEmpty(record.getQARatio())) {
                        record.setQARatio(record.getQARatio().setScale(2, RoundingMode.HALF_UP));
                    }
                    if (ObjectUtil.isNotEmpty(record.getResponseRate())) {
                        record.setResponseRate(record.getResponseRate().setScale(2, RoundingMode.HALF_UP));
                    }
                    if (ObjectUtil.isNotEmpty(record.getReceptionVolume()) && record.getReceptionVolume().compareTo(record.getReceptionVolumeBase()) > 0) {
                        record.setReceptionVolumeDesc("合同约定为" + record.getReceptionVolumeBase().toPlainString() + "，此项绩效已超标");
                    }
                    if (ObjectUtil.isNotEmpty(record.getConversionRate()) && record.getConversionRate().compareTo(record.getConversionRateBase()) < 0) {
                        record.setConversionRateDesc("合同约定为" + record.getConversionRateBase().toPlainString() + "，此项绩效未达标");
                    }
                    if (ObjectUtil.isNotEmpty(record.getResponseTime()) && record.getResponseTime().compareTo(record.getResponseTimeBase()) > 0) {
                        record.setResponseTimeDesc("合同约定为" + record.getResponseTimeBase().toPlainString() + "，此项绩效未达标");
                    }
                    record.setDateStart(params.getCondition().getDateStart());
                    record.setDateEnd(params.getCondition().getDateEnd());
                }
            }
            return new PageUtils(resultPage);
        } else {
            throw new RRException("参数缺失");
        }
    }

    @Override
    public PageUtils warningPage(ParamsModel<YkfAccountInputRecordEntity> params) {
        if (ObjectUtil.isNotEmpty(params)
                && ObjectUtil.isNotEmpty(params.getCondition())
                && ObjectUtil.isNotEmpty(params.getCondition().getDateStart())
                && ObjectUtil.isNotEmpty(params.getCondition().getDateEnd())) {
            IPage<YkfAccountInputRecordEntity> page = new Query<YkfAccountInputRecordEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
//            List<Long> powerUserIds = sysUserService.getPowerUserIds();
//            params.getCondition().setCreateUserIds(powerUserIds);
            List<Long> powerSubAccountIds = sysUserService.getPowerSubAccountIds();
            if (ObjectUtil.isEmpty(powerSubAccountIds)) {
                return new PageUtils();
            } else {
                if (!powerSubAccountIds.contains(0L)) {
                    params.getCondition().setPowerSubAccountIds(powerSubAccountIds);
                }
            }
            List<Long> shopIds = sysUserService.getOneselfShopIds();
            if (ObjectUtil.isEmpty(shopIds)) {
                return new PageUtils();
            } else {
                if (!shopIds.contains(0L)) {
                    params.getCondition().setPowerShopIds(shopIds);
                }
            }
            IPage<YkfAccountInputRecordEntity> resultPage = baseMapper.warningPage(page, params.getCondition(), params.getSort());

            return new PageUtils(resultPage);
        } else {
            throw new RRException("参数缺失");
        }
    }

    @Override
    public PageUtils customerDataPage(ParamsModel<YkfAccountInputRecordEntity> params) {
        if (ObjectUtil.isNotEmpty(params)
                && ObjectUtil.isNotEmpty(params.getCondition())
                && ObjectUtil.isNotEmpty(params.getCondition().getDateStart())
                && ObjectUtil.isNotEmpty(params.getCondition().getDateEnd())) {
            IPage<YkfAccountInputRecordEntity> page = new Query<YkfAccountInputRecordEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
//            List<Long> powerUserIds = sysUserService.getPowerUserIds();
//            params.getCondition().setCreateUserIds(powerUserIds);
            List<Long> powerSubAccountIds = sysUserService.getPowerSubAccountIds();
            if (ObjectUtil.isEmpty(powerSubAccountIds)) {
                return new PageUtils();
            } else {
                if (!powerSubAccountIds.contains(0L)) {
                    params.getCondition().setPowerSubAccountIds(powerSubAccountIds);
                }
            }
            IPage<YkfAccountInputRecordEntity> resultPage = null;
            long days = DateUtil.betweenDay(params.getCondition().getDateStart(), params.getCondition().getDateEnd(), true) + 1;
            params.getCondition().setDays(new BigDecimal(days));
            if (ObjectUtil.isNotEmpty(params.getCondition().getUserId()) && ObjectUtil.isNotEmpty(params.getCondition().getDate())) {
                resultPage = baseMapper.customerDataPage3(page, params.getCondition(), params.getSort());
            } else if (ObjectUtil.isNotEmpty(params.getCondition().getUserId())) {
                resultPage = baseMapper.customerDataPage2(page, params.getCondition(), params.getSort());
            } else {
                resultPage = baseMapper.customerDataPage(page, params.getCondition(), params.getSort());
            }

            //查询总销售额
            if (ObjectUtil.isNotEmpty(resultPage) && ObjectUtil.isNotEmpty(resultPage.getRecords())) {
                for (YkfAccountInputRecordEntity record : resultPage.getRecords()) {
//                    record.setAverageReceptionVolume(record.getAverageReceptionVolume().divide(new BigDecimal(days), 0, RoundingMode.HALF_UP));
                    if (StrUtil.isNotBlank(record.getCustomGroup())) {
                        QueryWrapper<YkfDictDetailEntity> queryWrapper = new QueryWrapper<>();
                        queryWrapper.lambda().eq(YkfDictDetailEntity::getDictId, 1)
                                .eq(YkfDictDetailEntity::getVal, record.getCustomGroup())
                                .last("limit 1");
                        YkfDictDetailEntity one = dictDetailService.getOne(queryWrapper);
                        if (ObjectUtil.isNotEmpty(one)) {
                            record.setCustomGroupName(one.getName());
                            record.setCustomGroup(one.getName());
                        }
                    }
                    record.setDateStart(params.getCondition().getDateStart());
                    record.setDateEnd(params.getCondition().getDateEnd());
                }
            }
            return new PageUtils(resultPage);
        } else {
            throw new RRException("参数缺失");
        }
    }

    @Override
    public PageUtils personalCustomerDataPage(ParamsModel<YkfAccountInputRecordEntity> params) {
        if (ObjectUtil.isNotEmpty(params)
                && ObjectUtil.isNotEmpty(params.getCondition())
                && ObjectUtil.isNotEmpty(params.getCondition().getDateStart())
                && ObjectUtil.isNotEmpty(params.getCondition().getDateEnd())) {
            IPage<YkfAccountInputRecordEntity> page = new Query<YkfAccountInputRecordEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
            IPage<YkfAccountInputRecordEntity> resultPage = baseMapper.personalCustomerDataPage(page, params.getCondition());
            List<YkfAccountInputRecordEntity> list = baseMapper.personalSumCustomerDataPage(params.getCondition());
            Map<String, Object> map = new HashMap<>();
            if (ObjectUtil.isNotEmpty(list)) {
                map = BeanUtil.beanToMap(list.get(0));
            }
            return new PageUtils(resultPage, map);
        } else {
            throw new RRException("参数缺失");
        }
    }

    @Override
    public PageUtils personalServiceDataPage(ParamsModel<YkfAccountInputRecordEntity> params) {
        QueryWrapper<YkfAccountInputRecordEntity> queryWrapper = ParamUtils.createQueryWrapperByDefaultSort(params);
        if (ObjectUtil.isNotEmpty(params.getCondition().getDateStart())) {
            queryWrapper.lambda().ge(YkfAccountInputRecordEntity::getDate, params.getCondition().getDateStart());
        }
        if (ObjectUtil.isNotEmpty(params.getCondition().getDateEnd())) {
            queryWrapper.lambda().le(YkfAccountInputRecordEntity::getDate, params.getCondition().getDateEnd());
        }
        IPage<YkfAccountInputRecordEntity> iPage = new Query<YkfAccountInputRecordEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
        //过滤userId
        QueryWrapper<YkfCustomerSubAccountEntity> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(YkfCustomerSubAccountEntity::getUserId, params.getCondition().getUserId());
        List<YkfCustomerSubAccountEntity> list = subAccountService.list(queryWrapper1);
        if (ObjectUtil.isNotEmpty(list)) {
            List<Long> subAccountIds = list.stream().map(YkfCustomerSubAccountEntity::getSubAccountId).collect(Collectors.toList());
            queryWrapper.lambda().in(YkfAccountInputRecordEntity::getSubAccountId, subAccountIds);
            IPage<YkfAccountInputRecordEntity> page = this.page(
                    iPage,
                    queryWrapper
            );
            List<YkfAccountInputSumModel> inputSumModels = baseMapper.personalSumCustomer(params.getCondition());
            YkfAccountInputSumModel sumModel = new YkfAccountInputSumModel();
            if (ObjectUtil.isNotEmpty(inputSumModels)) {
                sumModel = inputSumModels.get(0);
            }
            return new PageUtils(page, BeanUtil.beanToMap(sumModel));
        } else {
            return new PageUtils(iPage);
        }
    }

    /**
     * 提成核对表
     *
     * @param condition
     * @return
     */
    @Override
    public List<CommissionModel> personalCommissionCheckPage(YkfAccountInputRecordEntity condition) {
        Long userId = condition.getUserId();
        String month = condition.getMonth();
        DateTime monthDate = DateUtil.parse(month, "yyyy-MM");
        QueryWrapper<YkfAccountInputRecordEntity> inputRecordQueryWrapper = new QueryWrapper<>();
        boolean masterCompany = sysUserService.isMasterCompany();
        //计算月份首日日期和尾日日期
        DateTime startDate = DateUtil.beginOfMonth(monthDate);
        DateTime endDate = DateUtil.endOfMonth(monthDate);
        long days = DateUtil.betweenDay(startDate, endDate, true) + 1;
        QueryWrapper<YkfCustomerSubAccountEntity> subQueryWrapper = new QueryWrapper<>();
        subQueryWrapper.lambda().eq(YkfCustomerSubAccountEntity::getUserId, userId);
        List<YkfCustomerSubAccountEntity> list4 = subAccountService.list(subQueryWrapper);
        if (ObjectUtil.isEmpty(list4)) {
            return new ArrayList<>();
        }
        List<Long> subAccountIds = list4.stream().map(YkfCustomerSubAccountEntity::getSubAccountId).collect(Collectors.toList());
        inputRecordQueryWrapper.lambda().in(YkfAccountInputRecordEntity::getSubAccountId, subAccountIds)
                .ge(YkfAccountInputRecordEntity::getDate, startDate)
                .le(YkfAccountInputRecordEntity::getDate, endDate);
        List<YkfAccountInputRecordEntity> list = this.list(inputRecordQueryWrapper);
        List<CommissionModel> resultList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(list)) {
            Map<Long, List<YkfAccountInputRecordEntity>> collect = list.stream().collect(Collectors.groupingBy(YkfAccountInputRecordEntity::getSubAccountId));
            List<Long> subIds = new ArrayList<>(collect.keySet());

            //查询底薪提成记录
            QueryWrapper<YkfSubAccountRecordEntity> subAccountRecordQueryWrapper = new QueryWrapper<>();
            subAccountRecordQueryWrapper.lambda().le(YkfSubAccountRecordEntity::getCreateTime, endDate)
                    .in(YkfSubAccountRecordEntity::getSubAccountId, subIds)
                    .orderByAsc(YkfSubAccountRecordEntity::getCreateTime);
            List<YkfSubAccountRecordEntity> list1 = subAccountRecordService.list(subAccountRecordQueryWrapper);
            Map<String, List<YkfSubAccountRecordEntity>> collect1 = list1.stream().collect(Collectors.groupingBy(o -> DateUtil.formatDate(o.getCreateTime())));
            List<String> dateList = collect1.keySet().stream().sorted().collect(Collectors.toList());
            SysUserEntity user = sysUserService.getById(userId);
            //分段计算提成
            for (Long subId : subIds) {
                CommissionModel model = new CommissionModel();
                //总底薪收益
                BigDecimal sumConventionSalary = BigDecimal.ZERO;
                //总提成收益
                BigDecimal sumCommissionSalary = BigDecimal.ZERO;
                //总提成收益
                BigDecimal sumSaleSalary = BigDecimal.ZERO;
                YkfCustomerSubAccountEntity subAccount = subAccountService.getById(subId);
                if (masterCompany) {
                    subAccount.setConventionSalary(subAccount.getCompanyBaseSalary());
                }
                List<YkfAccountInputRecordEntity> list2 = collect.get(subId);
                for (YkfAccountInputRecordEntity record : list2) {
                    //匹配并计算提成,查询加班效益
                    Map<String, BigDecimal> map = countCommission(record, dateList, collect1, days);
                    sumConventionSalary = sumConventionSalary.add(map.get("conventionSalary"));
                    sumCommissionSalary = sumCommissionSalary.add(map.get("commissionSalary"));
                    sumSaleSalary = sumSaleSalary.add(record.getSalesRevenue());
                }
                if (ObjectUtil.isNotEmpty(subAccount)) {
                    model.setBaseSalary(subAccount.getConventionSalary());
                    model.setExNameLabel(subAccount.getExNameLabel());
                    model.setShopName(subAccount.getShopName());
                    model.setAccountName(subAccount.getAccountName());
                    model.setStartDate(DateUtil.formatDate(subAccount.getStartDate()));
                    model.setEndDate(DateUtil.formatDate(subAccount.getEndDate()));
                    model.setCommissionRatio(subAccount.getCommissionRatio());
                    model.setName(subAccount.getName());
                    model.setFlowerName(subAccount.getFlowerName());
                    model.setGroupNo(subAccount.getGroupNo());
                    model.setNo(subAccount.getNo());
                }
                model.setCustomGroupName(user.getCustomGroupName());
                model.setPestName(user.getPestName());
                model.setOnDutyStatus(user.getOnDutyStatus());
                model.setEntryDate(user.getEntryDate() != null ? DateUtil.formatDate(user.getEntryDate()) : "");
                model.setBecomeRegularStatus(user.getBecomeRegularStatus());
                model.setBecomeRegulardDate(user.getBecomeRegulardDate() != null ? DateUtil.formatDate(user.getBecomeRegulardDate()) : "");

                //计算工作天数
                Date start;
                Date end;
                if (startDate.compareTo(subAccount.getStartDate()) > 0) {
                    start = startDate;
                } else {
                    start = subAccount.getStartDate();
                }
                if (endDate.compareTo(subAccount.getEndDate()) < 0) {
                    DateTime date = DateUtil.date();
                    if (date.compareTo(endDate) < 0) {
                        end = date;
                    } else {
                        end = endDate;
                    }
                } else {
                    end = subAccount.getEndDate();
                }
                long workDays = DateUtil.betweenDay(start, end, false) + 1;

                model.setWorkDays((int) workDays);
                model.setMonthSalary(sumSaleSalary);
                model.setBaseProfit(sumConventionSalary);
                model.setCommissionProfit(sumCommissionSalary);

                //查询加班效益
                QueryWrapper<YkfWorkOvertimeRecordEntity> workRecordQueryWrapper = new QueryWrapper<>();
                workRecordQueryWrapper.lambda().ge(YkfWorkOvertimeRecordEntity::getStartDate, startDate)
                        .le(YkfWorkOvertimeRecordEntity::getEndDate, endDate)
                        .eq(YkfWorkOvertimeRecordEntity::getUserId, userId);
                List<YkfWorkOvertimeRecordEntity> list3 = workOvertimeRecordService.list(workRecordQueryWrapper);

                BigDecimal sumWorkOverSalary = BigDecimal.ZERO;
                if (ObjectUtil.isNotEmpty(list3)) {
                    for (YkfWorkOvertimeRecordEntity recordEntity : list3) {
                        sumWorkOverSalary = sumWorkOverSalary.add(recordEntity.getOvertimeSalary());
                    }
                }
                //效益合计=底薪效益+提成效益+加班效益
                BigDecimal sumSalary = sumConventionSalary.add(sumCommissionSalary).add(sumWorkOverSalary);
                model.setSumProfit(sumSalary);
                //查询基数，系数
                if (ObjectUtil.isNotEmpty(subAccount)) {
                    QueryWrapper<YkfCustomPostCommissionEntity> postCommissionQueryWrapper = new QueryWrapper<>();
                    if (StrUtil.equals(subAccount.getCompanyNo(), "ALL")) {
                        postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, subAccount.getCompanyNo())
                                .eq(YkfCustomPostCommissionEntity::getCustomPostType, user.getCustomPostType())
                                .last("limit 1");
                    } else {
                        postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, subAccount.getCompanyNo())
                                .last("limit 1");
                    }
                    YkfCustomPostCommissionEntity postCommission = postCommissionService.getOne(postCommissionQueryWrapper);
                    if (ObjectUtil.isNotEmpty(postCommission)) {
                        //基数
                        BigDecimal base = postCommission.getBase();
                        model.setBase(base);
                        //系数
                        BigDecimal coefficient = postCommission.getCoefficient();
                        model.setCoefficient(coefficient);
                        //提成工资=（效益合计-基数）*系数
                        BigDecimal salary = (sumSalary.subtract(base)).multiply(coefficient).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                        model.setCommissionSalary(salary.compareTo(BigDecimal.ZERO) >= 0 ? salary : BigDecimal.ZERO);
                    }
                }
                resultList.add(model);
            }
        }
        return resultList;
    }


    /**
     * 提成核对表
     *
     * @param req
     * @return
     */
    @Override
    public List<CommissionModel> personalCommissionCheckList(ExcelReq req) {
        Long userId = CommonUtils.getUserId();
        boolean masterCompany = sysUserService.isMasterCompany();
        String month = req.getMonth();
        DateTime monthDate = DateUtil.parse(month, "yyyy-MM");
        QueryWrapper<YkfAccountInputRecordEntity> inputRecordQueryWrapper = new QueryWrapper<>();
        //计算月份首日日期和尾日日期
        DateTime startDate = DateUtil.beginOfMonth(monthDate);
        DateTime endDate = DateUtil.endOfMonth(monthDate);
        long days = DateUtil.betweenDay(startDate, endDate, true) + 1;
        QueryWrapper<YkfCustomerSubAccountEntity> subQueryWrapper = new QueryWrapper<>();
        subQueryWrapper.lambda().eq(YkfCustomerSubAccountEntity::getUserId, userId);
        List<YkfCustomerSubAccountEntity> list4 = subAccountService.list(subQueryWrapper);
        if (ObjectUtil.isEmpty(list4)) {
            return new ArrayList<>();
        }
        List<Long> subAccountIds = list4.stream().map(YkfCustomerSubAccountEntity::getSubAccountId).collect(Collectors.toList());
        inputRecordQueryWrapper.lambda().in(YkfAccountInputRecordEntity::getSubAccountId, subAccountIds)
                .ge(YkfAccountInputRecordEntity::getDate, startDate)
                .le(YkfAccountInputRecordEntity::getDate, endDate);
        List<YkfAccountInputRecordEntity> list = this.list(inputRecordQueryWrapper);
        List<CommissionModel> resultList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(list)) {
            Map<Long, List<YkfAccountInputRecordEntity>> collect = list.stream().collect(Collectors.groupingBy(YkfAccountInputRecordEntity::getSubAccountId));
            List<Long> subIds = new ArrayList<>(collect.keySet());

            //查询底薪提成记录
            QueryWrapper<YkfSubAccountRecordEntity> subAccountRecordQueryWrapper = new QueryWrapper<>();
            subAccountRecordQueryWrapper.lambda().le(YkfSubAccountRecordEntity::getCreateTime, endDate)
                    .in(YkfSubAccountRecordEntity::getSubAccountId, subIds)
                    .orderByAsc(YkfSubAccountRecordEntity::getCreateTime);
            List<YkfSubAccountRecordEntity> list1 = subAccountRecordService.list(subAccountRecordQueryWrapper);
            Map<String, List<YkfSubAccountRecordEntity>> collect1 = list1.stream().collect(Collectors.groupingBy(o -> DateUtil.formatDate(o.getCreateTime())));
            List<String> dateList = collect1.keySet().stream().sorted().collect(Collectors.toList());
            SysUserEntity user = sysUserService.getById(userId);
            //分段计算提成
            for (Long subId : subIds) {
                CommissionModel model = new CommissionModel();
                //总底薪收益
                BigDecimal sumConventionSalary = BigDecimal.ZERO;
                //总提成收益
                BigDecimal sumCommissionSalary = BigDecimal.ZERO;
                //总提成收益
                BigDecimal sumSaleSalary = BigDecimal.ZERO;
                YkfCustomerSubAccountEntity subAccount = subAccountService.getById(subId);
                if (masterCompany) {
                    subAccount.setConventionSalary(subAccount.getCompanyBaseSalary());
                }
                List<YkfAccountInputRecordEntity> list2 = collect.get(subId);
                for (YkfAccountInputRecordEntity record : list2) {
                    //匹配并计算提成,查询加班效益
                    Map<String, BigDecimal> map = countCommission(record, dateList, collect1, days);
                    sumConventionSalary = sumConventionSalary.add(map.get("conventionSalary"));
                    sumCommissionSalary = sumCommissionSalary.add(map.get("commissionSalary"));
                    sumSaleSalary = sumSaleSalary.add(record.getSalesRevenue());
                }
                if (ObjectUtil.isNotEmpty(subAccount)) {
                    model.setBaseSalary(subAccount.getConventionSalary());
                    model.setExNameLabel(subAccount.getExNameLabel());
                    model.setShopName(subAccount.getShopName());
                    model.setAccountName(subAccount.getAccountName());
                    model.setStartDate(DateUtil.formatDate(subAccount.getStartDate()));
                    model.setEndDate(DateUtil.formatDate(subAccount.getEndDate()));
                    model.setCommissionRatio(subAccount.getCommissionRatio());
                    model.setName(subAccount.getName());
                    model.setFlowerName(subAccount.getFlowerName());
                    model.setGroupNo(subAccount.getGroupNo());
                    model.setNo(subAccount.getNo());
                }
                model.setCustomGroupName(user.getCustomGroupName());
                model.setPestName(user.getPestName());
                model.setOnDutyStatus(user.getOnDutyStatus());
                model.setEntryDate(user.getEntryDate() != null ? DateUtil.formatDate(user.getEntryDate()) : "");
                model.setBecomeRegularStatus(user.getBecomeRegularStatus());
                model.setBecomeRegulardDate(user.getBecomeRegulardDate() != null ? DateUtil.formatDate(user.getBecomeRegulardDate()) : "");

                //计算工作天数
                Date start;
                Date end;
                if (startDate.compareTo(subAccount.getStartDate()) > 0) {
                    start = startDate;
                } else {
                    start = subAccount.getStartDate();
                }
                if (endDate.compareTo(subAccount.getEndDate()) < 0) {
                    DateTime date = DateUtil.date();
                    if (date.compareTo(endDate) < 0) {
                        end = date;
                    } else {
                        end = endDate;
                    }
                } else {
                    end = subAccount.getEndDate();
                }
                long workDays = DateUtil.betweenDay(start, end, false) + 1;

                model.setWorkDays((int) workDays);
                model.setMonthSalary(sumSaleSalary);
                model.setBaseProfit(sumConventionSalary);
                model.setCommissionProfit(sumCommissionSalary);

                //查询加班效益
                QueryWrapper<YkfWorkOvertimeRecordEntity> workRecordQueryWrapper = new QueryWrapper<>();
                workRecordQueryWrapper.lambda().ge(YkfWorkOvertimeRecordEntity::getStartDate, startDate)
                        .le(YkfWorkOvertimeRecordEntity::getEndDate, endDate)
                        .eq(YkfWorkOvertimeRecordEntity::getUserId, userId);
                List<YkfWorkOvertimeRecordEntity> list3 = workOvertimeRecordService.list(workRecordQueryWrapper);

                BigDecimal sumWorkOverSalary = BigDecimal.ZERO;
                if (ObjectUtil.isNotEmpty(list3)) {
                    for (YkfWorkOvertimeRecordEntity recordEntity : list3) {
                        sumWorkOverSalary = sumWorkOverSalary.add(recordEntity.getOvertimeSalary());
                    }
                }
                //效益合计=底薪效益+提成效益+加班效益
                BigDecimal sumSalary = sumConventionSalary.add(sumCommissionSalary).add(sumWorkOverSalary);
                model.setSumProfit(sumSalary);
                //查询基数，系数
                if (ObjectUtil.isNotEmpty(subAccount)) {
                    QueryWrapper<YkfCustomPostCommissionEntity> postCommissionQueryWrapper = new QueryWrapper<>();
                    if (StrUtil.equals(subAccount.getCompanyNo(), "ALL")) {
                        postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, subAccount.getCompanyNo())
                                .eq(YkfCustomPostCommissionEntity::getCustomPostType, user.getCustomPostType())
                                .last("limit 1");
                    } else {
                        postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, subAccount.getCompanyNo())
                                .last("limit 1");
                    }
                    YkfCustomPostCommissionEntity postCommission = postCommissionService.getOne(postCommissionQueryWrapper);
                    if (ObjectUtil.isNotEmpty(postCommission)) {
                        //基数
                        BigDecimal base = postCommission.getBase();
                        model.setBase(base);
                        //系数
                        BigDecimal coefficient = postCommission.getCoefficient();
                        model.setCoefficient(coefficient);
                        //提成工资=（效益合计-基数）*系数
                        BigDecimal salary = (sumSalary.subtract(base)).multiply(coefficient).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                        model.setCommissionSalary(salary.compareTo(BigDecimal.ZERO) >= 0 ? salary : BigDecimal.ZERO);
                    }
                }
                resultList.add(model);
            }
        }
        return resultList;
    }


    /**
     * 提成核对表
     *
     * @param condition
     * @return
     */
    @Override
    public List<CommissionModel> commissionCheckPage(YkfAccountInputRecordEntity condition) {
        List<CommissionModel> resultList = new ArrayList<>();
        String keyword = condition.getKeyword();
        String month = condition.getMonth();
        DateTime monthDate = DateUtil.parse(month, "yyyy-MM");
        QueryWrapper<YkfAccountInputRecordEntity> inputRecordQueryWrapper = new QueryWrapper<>();
        //计算月份首日日期和尾日日期
        DateTime startDate = DateUtil.beginOfMonth(monthDate);
        DateTime endDate = DateUtil.endOfMonth(monthDate);
        long days = DateUtil.betweenDay(startDate, endDate, true) + 1;
        QueryWrapper<YkfCustomerSubAccountEntity> subQueryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(keyword)) {
            //查询符合条件的用户
            QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().and(wrapper -> wrapper.like(SysUserEntity::getFlowerName, keyword)
                    .or().like(SysUserEntity::getName, keyword));
            List<SysUserEntity> list = sysUserService.list(queryWrapper);
            if (ObjectUtil.isNotEmpty(list)) {
                List<Long> userIds = list.stream().map(SysUserEntity::getUserId).collect(Collectors.toList());
                subQueryWrapper.lambda().and(wrapper -> wrapper.in(YkfCustomerSubAccountEntity::getUserId, userIds)
                        .or().like(YkfCustomerSubAccountEntity::getNo, keyword));
            } else {
                return new ArrayList<>();
            }
        }
        subQueryWrapper.lambda().ge(YkfCustomerSubAccountEntity::getEndDate, startDate)
                .le(YkfCustomerSubAccountEntity::getStartDate, endDate);
        List<Long> powerSubAccountIds = sysUserService.getPowerSubAccountIds();
        if (ObjectUtil.isEmpty(powerSubAccountIds)) {
            return new ArrayList<>();
        } else {
            if (!powerSubAccountIds.contains(0L)) {
                subQueryWrapper.lambda().in(YkfCustomerSubAccountEntity::getSubAccountId, powerSubAccountIds);
            }
        }
        boolean masterCompany = sysUserService.isMasterCompany();
        List<YkfCustomerSubAccountEntity> list4 = subAccountService.list(subQueryWrapper);
        if (ObjectUtil.isNotEmpty(list4)) {
            //查询所有的数据记录
            List<Long> subAccountIds = list4.stream().map(YkfCustomerSubAccountEntity::getSubAccountId).distinct().collect(Collectors.toList());
            QueryWrapper<YkfAccountInputRecordEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(YkfAccountInputRecordEntity::getSubAccountId, subAccountIds)
                    .ge(YkfAccountInputRecordEntity::getDate, startDate)
                    .le(YkfAccountInputRecordEntity::getDate, endDate);
            List<YkfAccountInputRecordEntity> list5 = this.list(queryWrapper);
            Map<Long, List<YkfAccountInputRecordEntity>> map = new HashMap<>();
            if (ObjectUtil.isNotEmpty(list5)) {
                map = list5.stream().collect(Collectors.groupingBy(YkfAccountInputRecordEntity::getSubAccountId));
            }
            for (YkfCustomerSubAccountEntity subAccount : list4) {
                if (masterCompany) {
                    subAccount.setConventionSalary(subAccount.getCompanyBaseSalary());
                }
                CommissionModel model = new CommissionModel();
                //总底薪收益
                BigDecimal sumConventionSalary = BigDecimal.ZERO;
                //总提成收益
                BigDecimal sumCommissionSalary = BigDecimal.ZERO;
                //总提成收益
                BigDecimal sumSaleSalary = BigDecimal.ZERO;

                Long userId = subAccount.getUserId();
                model.setBaseSalary(subAccount.getConventionSalary());
                model.setExNameLabel(subAccount.getExNameLabel());
                model.setShopName(subAccount.getShopName());
                model.setAccountName(subAccount.getAccountName());
                model.setStartDate(DateUtil.formatDate(subAccount.getStartDate()));
                model.setEndDate(DateUtil.formatDate(subAccount.getEndDate()));
                model.setCommissionRatio(subAccount.getCommissionRatio());
                model.setName(subAccount.getName());
                model.setFlowerName(subAccount.getFlowerName());
                model.setGroupNo(subAccount.getGroupNo());
                model.setNo(subAccount.getNo());
                model.setPlatformName(subAccount.getPlatformName());
                SysUserEntity user = sysUserService.getById(userId);
                if (ObjectUtil.isNotEmpty(user)) {
                    model.setCustomGroupName(user.getCustomGroupName());
                    model.setPestName(user.getPestName());
                    model.setOnDutyStatus(user.getOnDutyStatus());
                    model.setEntryDate(user.getEntryDate() != null ? DateUtil.formatDate(user.getEntryDate()) : "");
                    model.setBecomeRegularStatus(user.getBecomeRegularStatus());
                    model.setBecomeRegulardDate(user.getBecomeRegulardDate() != null ? DateUtil.formatDate(user.getBecomeRegulardDate()) : "");
                    model.setCustomTypeName(user.getCustomPostTypeName());
                }
                List<YkfAccountInputRecordEntity> list = map.get(subAccount.getSubAccountId());
                if (ObjectUtil.isNotEmpty(list) && !list.isEmpty()) {
                    for (YkfAccountInputRecordEntity record : list) {
                        sumSaleSalary = sumSaleSalary.add(getDecimalNotNull(record.getSalesRevenue()));
                    }
                    //计算工作天数
                    Date start;
                    Date end;
                    if (startDate.compareTo(subAccount.getStartDate()) > 0) {
                        start = startDate;
                    } else {
                        start = subAccount.getStartDate();
                    }
                    if (endDate.compareTo(subAccount.getEndDate()) < 0) {
                        DateTime date = DateUtil.date();
                        if (date.compareTo(endDate) < 0) {
                            end = date;
                        } else {
                            end = endDate;
                        }
                    } else {
                        end = subAccount.getEndDate();
                    }
                    long workDays = DateUtil.betweenDay(start, end, false) + 1;
                    sumConventionSalary = getDecimalNotNull(subAccount.getConventionSalary()).multiply(new BigDecimal(workDays).divide(new BigDecimal(days), 2, RoundingMode.HALF_UP));
                    model.setWorkDays((int) workDays);
                } else {
//                    model.setWorkDays(0);
                    continue;
                }
                //提成效益
                sumCommissionSalary = sumSaleSalary.multiply(getDecimalNotNull(subAccount.getCommissionRatio())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                model.setMonthSalary(sumSaleSalary);
                model.setBaseProfit(sumConventionSalary);
                model.setCommissionProfit(sumCommissionSalary);

                //查询加班效益
                QueryWrapper<YkfWorkOvertimeRecordEntity> workRecordQueryWrapper = new QueryWrapper<>();
                workRecordQueryWrapper.lambda().ge(YkfWorkOvertimeRecordEntity::getStartDate, startDate)
                        .le(YkfWorkOvertimeRecordEntity::getEndDate, endDate)
                        .eq(YkfWorkOvertimeRecordEntity::getUserId, userId);
                List<YkfWorkOvertimeRecordEntity> list3 = workOvertimeRecordService.list(workRecordQueryWrapper);

                BigDecimal sumWorkOverSalary = BigDecimal.ZERO;
                if (ObjectUtil.isNotEmpty(list3)) {
                    for (YkfWorkOvertimeRecordEntity recordEntity : list3) {
                        sumWorkOverSalary = sumWorkOverSalary.add(recordEntity.getOvertimeSalary());
                    }
                }
                //效益合计=底薪效益+提成效益+加班效益
                BigDecimal sumSalary = sumConventionSalary.add(sumCommissionSalary).add(sumWorkOverSalary);
                model.setSumProfit(sumSalary);
                //查询基数，系数
                if (ObjectUtil.isNotEmpty(subAccount)) {
                    QueryWrapper<YkfCustomPostCommissionEntity> postCommissionQueryWrapper = new QueryWrapper<>();
                    if (StrUtil.equals(subAccount.getCompanyNo(), "ALL")) {
                        postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, subAccount.getCompanyNo())
                                .eq(YkfCustomPostCommissionEntity::getCustomPostType, user.getCustomPostType())
                                .last("limit 1");
                    } else {
                        postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, subAccount.getCompanyNo())
                                .last("limit 1");
                    }
                    YkfCustomPostCommissionEntity postCommission = postCommissionService.getOne(postCommissionQueryWrapper);
                    if (ObjectUtil.isNotEmpty(postCommission)) {
                        //基数
                        BigDecimal base = postCommission.getBase();
                        model.setBase(base);
                        //系数
                        BigDecimal coefficient = postCommission.getCoefficient();
                        model.setCoefficient(coefficient);
                        //提成工资=（效益合计-基数）*系数
                        BigDecimal salary = (sumSalary.subtract(base)).multiply(coefficient).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                        model.setCommissionSalary(salary.compareTo(BigDecimal.ZERO) >= 0 ? salary : BigDecimal.ZERO);
                    }
                }
                resultList.add(model);
            }
        }
        return resultList;
    }

    /**
     * 提成核对表
     *
     * @param condition
     * @return
     */
    @Override
    public Map<String, Object> commissionCheckPage3(YkfAccountInputRecordEntity condition) {
        Map<String, Object> resultMap = new HashMap<>();
        List<CommissionModel> resultList = new ArrayList<>();
        String keyword = condition.getKeyword();
        String month = condition.getMonth();
        DateTime monthDate = DateUtil.parse(month, "yyyy-MM");
        QueryWrapper<YkfAccountInputRecordEntity> inputRecordQueryWrapper = new QueryWrapper<>();
        //计算月份首日日期和尾日日期
        DateTime startDate = DateUtil.beginOfMonth(monthDate);
        DateTime endDate = DateUtil.endOfMonth(monthDate);
        long days = DateUtil.betweenDay(startDate, endDate, true) + 1;
        QueryWrapper<YkfCustomerSubAccountEntity> subQueryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(keyword)) {
            //查询符合条件的用户
            QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().and(wrapper -> wrapper.like(SysUserEntity::getFlowerName, keyword)
                    .or().like(SysUserEntity::getName, keyword));
            List<SysUserEntity> list = sysUserService.list(queryWrapper);
            if (ObjectUtil.isNotEmpty(list)) {
                List<Long> userIds = list.stream().map(SysUserEntity::getUserId).collect(Collectors.toList());
                subQueryWrapper.lambda().and(wrapper -> wrapper.in(YkfCustomerSubAccountEntity::getUserId, userIds)
                        .or().like(YkfCustomerSubAccountEntity::getNo, keyword));
            } else {
                return new HashMap<>();
            }
        }
        subQueryWrapper.lambda().ge(YkfCustomerSubAccountEntity::getEndDate, startDate)
                .le(YkfCustomerSubAccountEntity::getStartDate, endDate);
        List<Long> powerSubAccountIds = sysUserService.getPowerSubAccountIds();
        if (ObjectUtil.isEmpty(powerSubAccountIds)) {
            return resultMap;
        } else {
            if (!powerSubAccountIds.contains(0L)) {
                subQueryWrapper.lambda().in(YkfCustomerSubAccountEntity::getSubAccountId, powerSubAccountIds);
            }
        }
        boolean masterCompany = sysUserService.isMasterCompany();
        subQueryWrapper.lambda().orderByAsc(YkfCustomerSubAccountEntity::getAccountNo);
        List<YkfCustomerSubAccountEntity> list4 = subAccountService.list(subQueryWrapper);
        if (ObjectUtil.isNotEmpty(list4)) {
            //查询所有的数据记录
            List<Long> subAccountIds = list4.stream().map(YkfCustomerSubAccountEntity::getSubAccountId).distinct().collect(Collectors.toList());
            QueryWrapper<YkfAccountInputRecordEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(YkfAccountInputRecordEntity::getSubAccountId, subAccountIds)
                    .ge(YkfAccountInputRecordEntity::getDate, startDate)
                    .le(YkfAccountInputRecordEntity::getDate, endDate);
            List<YkfAccountInputRecordEntity> list5 = this.list(queryWrapper);
            Map<Long, List<YkfAccountInputRecordEntity>> map = new HashMap<>();
            if (ObjectUtil.isNotEmpty(list5)) {
                map = list5.stream().collect(Collectors.groupingBy(YkfAccountInputRecordEntity::getSubAccountId));
            }
            for (YkfCustomerSubAccountEntity subAccount : list4) {
                if (masterCompany) {
                    subAccount.setConventionSalary(subAccount.getCompanyBaseSalary());
                }
                CommissionModel model = new CommissionModel();
                //总底薪收益
                BigDecimal sumConventionSalary = BigDecimal.ZERO;
                //总提成收益
                BigDecimal sumCommissionSalary = BigDecimal.ZERO;
                //总提成收益
                BigDecimal sumSaleSalary = BigDecimal.ZERO;

                Long userId = subAccount.getUserId();
                model.setBaseSalary(subAccount.getConventionSalary());
                model.setExNameLabel(subAccount.getExNameLabel());
                model.setShopName(subAccount.getShopName());
                model.setAccountName(subAccount.getAccountName());
                model.setStartDate(DateUtil.formatDate(subAccount.getStartDate()));
                model.setEndDate(DateUtil.formatDate(subAccount.getEndDate()));
                model.setCommissionRatio(subAccount.getCommissionRatio());
                YkfCustomerShopEntity shop = customerShopService.getById(subAccount.getShopId());
                if (ObjectUtil.isNotEmpty(shop)) {
                    model.setPlatformName(shop.getPlatformName());
                }
                SysUserEntity user = sysUserService.getById(userId);
                if (ObjectUtil.isNotEmpty(user)) {
                    model.setCustomGroupName(user.getCustomGroupName());
                    model.setPestName(user.getPestName());
                    model.setOnDutyStatus(user.getOnDutyStatus());
                    model.setEntryDate(user.getEntryDate() != null ? DateUtil.formatDate(user.getEntryDate()) : "");
                    model.setBecomeRegularStatus(user.getBecomeRegularStatus());
                    model.setBecomeRegulardDate(user.getBecomeRegulardDate() != null ? DateUtil.formatDate(user.getBecomeRegulardDate()) : "");
                    model.setCustomTypeName(user.getCustomPostTypeName());
                    model.setName(user.getName());
                    model.setFlowerName(user.getFlowerName());
                    model.setGroupNo(user.getGroupNo());
                    model.setNo(user.getNo());
                } else {
                    model.setName(subAccount.getName());
                    model.setFlowerName(subAccount.getFlowerName());
                    model.setGroupNo(subAccount.getGroupNo());
                    model.setNo(subAccount.getNo());
                }
                //计算工作天数
                Date start;
                Date end;
                if (startDate.compareTo(subAccount.getStartDate()) > 0) {
                    start = startDate;
                } else {
                    start = subAccount.getStartDate();
                }
                if (endDate.compareTo(subAccount.getEndDate()) < 0) {
                    DateTime date = DateUtil.date();
                    if (date.compareTo(endDate) < 0) {
                        end = date;
                    } else {
                        end = endDate;
                    }
                } else {
                    end = subAccount.getEndDate();
                }
                long workDays = DateUtil.betweenDay(start, end, false) + 1;

                sumConventionSalary = getDecimalNotNull(subAccount.getConventionSalary()).multiply(new BigDecimal(workDays)).divide(new BigDecimal(days), 2, RoundingMode.HALF_UP);
                model.setWorkDays((int) workDays);

                List<YkfAccountInputRecordEntity> list = map.get(subAccount.getSubAccountId());
                if (ObjectUtil.isNotEmpty(list) && !list.isEmpty()) {
                    for (YkfAccountInputRecordEntity record : list) {
                        sumSaleSalary = sumSaleSalary.add(getDecimalNotNull(record.getSalesRevenue()));
                    }
                } else {
                    sumSaleSalary = BigDecimal.ZERO;
                }
                //提成效益
                sumCommissionSalary = sumSaleSalary.multiply(getDecimalNotNull(subAccount.getCommissionRatio())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                model.setMonthSalary(sumSaleSalary);
                model.setBaseProfit(sumConventionSalary);
                model.setCommissionProfit(sumCommissionSalary);

                //查询加班效益
                QueryWrapper<YkfWorkOvertimeRecordEntity> workRecordQueryWrapper = new QueryWrapper<>();
                workRecordQueryWrapper.lambda().ge(YkfWorkOvertimeRecordEntity::getStartDate, startDate)
                        .le(YkfWorkOvertimeRecordEntity::getEndDate, endDate)
                        .eq(YkfWorkOvertimeRecordEntity::getUserId, userId);
                List<YkfWorkOvertimeRecordEntity> list3 = workOvertimeRecordService.list(workRecordQueryWrapper);

                BigDecimal sumWorkOverSalary = BigDecimal.ZERO;
                if (ObjectUtil.isNotEmpty(list3)) {
                    for (YkfWorkOvertimeRecordEntity recordEntity : list3) {
                        sumWorkOverSalary = sumWorkOverSalary.add(recordEntity.getOvertimeSalary());
                    }
                }
                //效益合计=底薪效益+提成效益+加班效益
                BigDecimal sumSalary = sumConventionSalary.add(sumCommissionSalary).add(sumWorkOverSalary);
                model.setSumProfit(sumSalary);
                //查询基数，系数
                if (ObjectUtil.isNotEmpty(subAccount)) {
                    QueryWrapper<YkfCustomPostCommissionEntity> postCommissionQueryWrapper = new QueryWrapper<>();
                    if (StrUtil.equals(subAccount.getCompanyNo(), "ALL")) {
                        postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, subAccount.getCompanyNo())
                                .eq(YkfCustomPostCommissionEntity::getCustomPostType, user.getCustomPostType())
                                .last("limit 1");
                    } else {
                        postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, subAccount.getCompanyNo())
                                .last("limit 1");
                    }
                    YkfCustomPostCommissionEntity postCommission = postCommissionService.getOne(postCommissionQueryWrapper);
                    if (ObjectUtil.isNotEmpty(postCommission)) {
                        //基数
                        BigDecimal base = postCommission.getBase();
                        model.setBase(base);
                        //系数
                        BigDecimal coefficient = postCommission.getCoefficient();
                        model.setCoefficient(coefficient);
                        //提成工资=（效益合计-基数）*系数
                        BigDecimal salary = (sumSalary.subtract(base)).multiply(coefficient).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                        model.setCommissionSalary(salary.compareTo(BigDecimal.ZERO) >= 0 ? salary : BigDecimal.ZERO);
                    }
                }
                resultList.add(model);
            }
        }
        resultList.sort(Comparator.comparing(CommissionModel::getAccountName).thenComparing(CommissionModel::getStartDate));
        resultMap.put("list", resultList);
        Map<String, BigDecimal> sumInfo = new HashMap<>();
        BigDecimal sumBaseProfit = BigDecimal.ZERO;
        BigDecimal sumMonthSalary = BigDecimal.ZERO;
        BigDecimal sumCommissionProfit = BigDecimal.ZERO;
        BigDecimal sumSumProfit = BigDecimal.ZERO;
        if (ObjectUtil.isNotEmpty(resultList)) {
            for (CommissionModel commissionModel : resultList) {
                commissionModel.setMonth(month);
                if (ObjectUtil.isNotEmpty(commissionModel.getBaseProfit())) {
                    sumBaseProfit = sumBaseProfit.add(commissionModel.getBaseProfit());
                }
                if (ObjectUtil.isNotEmpty(commissionModel.getMonthSalary())) {
                    sumMonthSalary = sumMonthSalary.add(commissionModel.getMonthSalary());
                }
                if (ObjectUtil.isNotEmpty(commissionModel.getCommissionProfit())) {
                    sumCommissionProfit = sumCommissionProfit.add(commissionModel.getCommissionProfit());
                }
                if (ObjectUtil.isNotEmpty(commissionModel.getSumProfit())) {
                    sumSumProfit = sumSumProfit.add(commissionModel.getSumProfit());
                }
            }
        }
        sumInfo.put("sumBaseProfit", sumBaseProfit.stripTrailingZeros());
        sumInfo.put("sumMonthSalary", sumMonthSalary.stripTrailingZeros());
        sumInfo.put("sumCommissionProfit", sumCommissionProfit.stripTrailingZeros());
        sumInfo.put("sumSumProfit", sumSumProfit.stripTrailingZeros());
        resultMap.put("sumInfo", sumInfo);
        return resultMap;
    }

    private static BigDecimal getDecimalNotNull(BigDecimal num) {
        return ObjectUtil.isEmpty(num) ? BigDecimal.ZERO : num;
    }


    /**
     * 提成核对表
     *
     * @param condition
     * @return
     */
    public List<CommissionModel> commissionCheckPage2(YkfAccountInputRecordEntity condition) {
        String keyword = condition.getKeyword();
        String month = condition.getMonth();
        DateTime monthDate = DateUtil.parse(month, "yyyy-MM");
        boolean masterCompany = sysUserService.isMasterCompany();
        QueryWrapper<YkfAccountInputRecordEntity> inputRecordQueryWrapper = new QueryWrapper<>();
        //计算月份首日日期和尾日日期
        DateTime startDate = DateUtil.beginOfMonth(monthDate);
        DateTime endDate = DateUtil.endOfMonth(monthDate);
        long days = DateUtil.betweenDay(startDate, endDate, true) + 1;
        QueryWrapper<YkfCustomerSubAccountEntity> subQueryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(keyword)) {
            subQueryWrapper.lambda().and(wrapper -> wrapper.like(YkfCustomerSubAccountEntity::getFlowerName, keyword)
                    .or().like(YkfCustomerSubAccountEntity::getName, keyword)
                    .or().like(YkfCustomerSubAccountEntity::getNo, keyword));
        }
        List<YkfCustomerSubAccountEntity> list4 = subAccountService.list(subQueryWrapper);
        if (ObjectUtil.isEmpty(list4)) {
            return new ArrayList<>();
        }
        List<Long> subAccountIds = list4.stream().map(YkfCustomerSubAccountEntity::getSubAccountId).distinct().collect(Collectors.toList());
        inputRecordQueryWrapper.lambda().in(YkfAccountInputRecordEntity::getSubAccountId, subAccountIds)
                .ge(YkfAccountInputRecordEntity::getDate, startDate)
                .le(YkfAccountInputRecordEntity::getDate, endDate);
        List<YkfAccountInputRecordEntity> list = this.list(inputRecordQueryWrapper);
        List<CommissionModel> resultList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(list)) {
            Map<Long, List<YkfAccountInputRecordEntity>> collect = list.stream().collect(Collectors.groupingBy(YkfAccountInputRecordEntity::getSubAccountId));
            List<Long> subIds = new ArrayList<>(collect.keySet());

            //查询底薪提成记录
            QueryWrapper<YkfSubAccountRecordEntity> subAccountRecordQueryWrapper = new QueryWrapper<>();
            subAccountRecordQueryWrapper.lambda().le(YkfSubAccountRecordEntity::getCreateTime, endDate)
                    .in(YkfSubAccountRecordEntity::getSubAccountId, subIds)
                    .orderByAsc(YkfSubAccountRecordEntity::getCreateTime);
            List<YkfSubAccountRecordEntity> list1 = subAccountRecordService.list(subAccountRecordQueryWrapper);
            Map<String, List<YkfSubAccountRecordEntity>> collect1 = list1.stream().collect(Collectors.groupingBy(o -> DateUtil.formatDate(o.getCreateTime())));
            List<String> dateList = collect1.keySet().stream().sorted().collect(Collectors.toList());
            //分段计算提成
            for (Long subId : subIds) {
                CommissionModel model = new CommissionModel();
                //总底薪收益
                BigDecimal sumConventionSalary = BigDecimal.ZERO;
                //总提成收益
                BigDecimal sumCommissionSalary = BigDecimal.ZERO;
                //总提成收益
                BigDecimal sumSaleSalary = BigDecimal.ZERO;
                YkfCustomerSubAccountEntity subAccount = subAccountService.getById(subId);
                if (masterCompany) {
                    subAccount.setConventionSalary(subAccount.getCompanyBaseSalary());
                }
                List<YkfAccountInputRecordEntity> list2 = collect.get(subId);
                Long userId = subAccount.getUserId();
                SysUserEntity user = sysUserService.getById(userId);
                for (YkfAccountInputRecordEntity record : list2) {
                    //匹配并计算提成,查询加班效益
                    Map<String, BigDecimal> map = countCommission(record, dateList, collect1, days);
                    sumConventionSalary = sumConventionSalary.add(map.get("conventionSalary"));
                    sumCommissionSalary = sumCommissionSalary.add(map.get("commissionSalary"));
                    sumSaleSalary = sumSaleSalary.add(record.getSalesRevenue());
                }
                if (ObjectUtil.isNotEmpty(subAccount)) {
                    model.setBaseSalary(subAccount.getConventionSalary());
                    model.setExNameLabel(subAccount.getExNameLabel());
                    model.setShopName(subAccount.getShopName());
                    model.setAccountName(subAccount.getAccountName());
                    model.setStartDate(DateUtil.formatDate(subAccount.getStartDate()));
                    model.setEndDate(DateUtil.formatDate(subAccount.getEndDate()));
                    model.setCommissionRatio(subAccount.getCommissionRatio());
                    model.setName(subAccount.getName());
                    model.setFlowerName(subAccount.getFlowerName());
                    model.setGroupNo(subAccount.getGroupNo());
                    model.setNo(subAccount.getNo());
                }
                if (ObjectUtil.isNotEmpty(user)) {
                    model.setCustomGroupName(user.getCustomGroupName());
                    model.setPestName(user.getPestName());
                    model.setOnDutyStatus(user.getOnDutyStatus());
                    model.setEntryDate(user.getEntryDate() != null ? DateUtil.formatDate(user.getEntryDate()) : "");
                    model.setBecomeRegularStatus(user.getBecomeRegularStatus());
                    model.setBecomeRegulardDate(user.getBecomeRegulardDate() != null ? DateUtil.formatDate(user.getBecomeRegulardDate()) : "");
                }
                //计算工作天数
                Date start;
                Date end;
                if (startDate.compareTo(subAccount.getStartDate()) > 0) {
                    start = startDate;
                } else {
                    start = subAccount.getStartDate();
                }
                if (endDate.compareTo(subAccount.getEndDate()) < 0) {
                    DateTime date = DateUtil.date();
                    if (date.compareTo(endDate) < 0) {
                        end = date;
                    } else {
                        end = endDate;
                    }
                } else {
                    end = subAccount.getEndDate();
                }
                long workDays = DateUtil.betweenDay(start, end, false) + 1;

                model.setWorkDays((int) workDays);
                model.setMonthSalary(sumSaleSalary);
                model.setBaseProfit(sumConventionSalary);
                model.setCommissionProfit(sumCommissionSalary);

                //查询加班效益
                QueryWrapper<YkfWorkOvertimeRecordEntity> workRecordQueryWrapper = new QueryWrapper<>();
                workRecordQueryWrapper.lambda().ge(YkfWorkOvertimeRecordEntity::getStartDate, startDate)
                        .le(YkfWorkOvertimeRecordEntity::getEndDate, endDate)
                        .eq(YkfWorkOvertimeRecordEntity::getUserId, userId);
                List<YkfWorkOvertimeRecordEntity> list3 = workOvertimeRecordService.list(workRecordQueryWrapper);

                BigDecimal sumWorkOverSalary = BigDecimal.ZERO;
                if (ObjectUtil.isNotEmpty(list3)) {
                    for (YkfWorkOvertimeRecordEntity recordEntity : list3) {
                        sumWorkOverSalary = sumWorkOverSalary.add(recordEntity.getOvertimeSalary());
                    }
                }
                //效益合计=底薪效益+提成效益+加班效益
                BigDecimal sumSalary = sumConventionSalary.add(sumCommissionSalary).add(sumWorkOverSalary);
                model.setSumProfit(sumSalary);
                //查询基数，系数
                if (ObjectUtil.isNotEmpty(subAccount)) {
                    QueryWrapper<YkfCustomPostCommissionEntity> postCommissionQueryWrapper = new QueryWrapper<>();
                    if (StrUtil.equals(subAccount.getCompanyNo(), "ALL")) {
                        postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, subAccount.getCompanyNo())
                                .eq(YkfCustomPostCommissionEntity::getCustomPostType, user.getCustomPostType())
                                .last("limit 1");
                    } else {
                        postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, subAccount.getCompanyNo())
                                .last("limit 1");
                    }
                    YkfCustomPostCommissionEntity postCommission = postCommissionService.getOne(postCommissionQueryWrapper);
                    if (ObjectUtil.isNotEmpty(postCommission)) {
                        //基数
                        BigDecimal base = postCommission.getBase();
                        model.setBase(base);
                        //系数
                        BigDecimal coefficient = postCommission.getCoefficient();
                        model.setCoefficient(coefficient);
                        //提成工资=（效益合计-基数）*系数
                        BigDecimal salary = (sumSalary.subtract(base)).multiply(coefficient).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                        model.setCommissionSalary(salary.compareTo(BigDecimal.ZERO) >= 0 ? salary : BigDecimal.ZERO);
                    }
                }
                resultList.add(model);
            }
        }
        return resultList;
    }

    /**
     * 提成核对表
     *
     * @param condition
     * @return
     */
    @Override
    public List<CommissionModel> commissionCheckForShop(YkfCustomerShopEntity condition) {
        List<CommissionModel> resultList = new ArrayList<>();
        String keyword = condition.getKeyword();
        String month = condition.getMonth();
        DateTime monthDate = DateUtil.parse(month, "yyyy-MM");
        //计算月份首日日期和尾日日期
        DateTime startDate = DateUtil.beginOfMonth(monthDate);
        DateTime endDate = DateUtil.endOfMonth(monthDate);
        long days = DateUtil.betweenDay(startDate, endDate, true) + 1;
        QueryWrapper<YkfCustomerSubAccountEntity> subQueryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(keyword)) {
            subQueryWrapper.lambda().and(wrapper -> wrapper.like(YkfCustomerSubAccountEntity::getFlowerName, keyword)
                    .or().like(YkfCustomerSubAccountEntity::getName, keyword)
                    .or().like(YkfCustomerSubAccountEntity::getNo, keyword));
        }
        boolean masterCompany = sysUserService.isMasterCompany();
        subQueryWrapper.lambda().ge(YkfCustomerSubAccountEntity::getEndDate, startDate)
                .le(YkfCustomerSubAccountEntity::getStartDate, endDate)
                .eq(YkfCustomerSubAccountEntity::getShopId, condition.getShopId());
        List<YkfCustomerSubAccountEntity> list4 = subAccountService.list(subQueryWrapper);
        if (ObjectUtil.isNotEmpty(list4)) {
            //查询所有的数据记录
            List<Long> subAccountIds = list4.stream().map(YkfCustomerSubAccountEntity::getSubAccountId).distinct().collect(Collectors.toList());
            QueryWrapper<YkfAccountInputRecordEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(YkfAccountInputRecordEntity::getSubAccountId, subAccountIds)
                    .ge(YkfAccountInputRecordEntity::getDate, startDate)
                    .le(YkfAccountInputRecordEntity::getDate, endDate);
            List<YkfAccountInputRecordEntity> list5 = this.list(queryWrapper);
            Map<Long, List<YkfAccountInputRecordEntity>> map = new HashMap<>();
            if (ObjectUtil.isNotEmpty(list5)) {
                map = list5.stream().collect(Collectors.groupingBy(YkfAccountInputRecordEntity::getSubAccountId));
            }
            for (YkfCustomerSubAccountEntity subAccount : list4) {
                if (masterCompany) {
                    subAccount.setConventionSalary(subAccount.getCompanyBaseSalary());
                }
                CommissionModel model = new CommissionModel();
                //总底薪收益
                BigDecimal sumConventionSalary = BigDecimal.ZERO;
                //总提成收益
                BigDecimal sumCommissionSalary = BigDecimal.ZERO;
                //总提成收益
                BigDecimal sumSaleSalary = BigDecimal.ZERO;

                Long userId = subAccount.getUserId();
                model.setBaseSalary(subAccount.getConventionSalary());
                model.setExNameLabel(subAccount.getExNameLabel());
                model.setShopName(subAccount.getShopName());
                model.setAccountName(subAccount.getAccountName());
                model.setStartDate(DateUtil.formatDate(subAccount.getStartDate()));
                model.setEndDate(DateUtil.formatDate(subAccount.getEndDate()));
                model.setCommissionRatio(subAccount.getCommissionRatio());
                model.setName(subAccount.getName());
                model.setFlowerName(subAccount.getFlowerName());
                model.setGroupNo(subAccount.getGroupNo());
                model.setNo(subAccount.getNo());
                SysUserEntity user = sysUserService.getById(userId);
                if (ObjectUtil.isNotEmpty(user)) {
                    model.setCustomGroupName(user.getCustomGroupName());
                    model.setPestName(user.getPestName());
                    model.setOnDutyStatus(user.getOnDutyStatus());
                    model.setEntryDate(user.getEntryDate() != null ? DateUtil.formatDate(user.getEntryDate()) : "");
                    model.setBecomeRegularStatus(user.getBecomeRegularStatus());
                    model.setBecomeRegulardDate(user.getBecomeRegulardDate() != null ? DateUtil.formatDate(user.getBecomeRegulardDate()) : "");
                }
                List<YkfAccountInputRecordEntity> list = map.get(subAccount.getSubAccountId());
                if (ObjectUtil.isNotEmpty(list) && !list.isEmpty()) {
                    for (YkfAccountInputRecordEntity record : list) {
                        sumSaleSalary = sumSaleSalary.add(getDecimalNotNull(record.getSalesRevenue()));
                    }
                    //计算工作天数
                    Date start;
                    Date end;
                    if (startDate.compareTo(subAccount.getStartDate()) > 0) {
                        start = startDate;
                    } else {
                        start = subAccount.getStartDate();
                    }
                    if (endDate.compareTo(subAccount.getEndDate()) < 0) {
                        DateTime date = DateUtil.date();
                        if (date.compareTo(endDate) < 0) {
                            end = date;
                        } else {
                            end = endDate;
                        }
                    } else {
                        end = subAccount.getEndDate();
                    }
                    long workDays = DateUtil.betweenDay(start, end, false) + 1;

                    model.setWorkDays((int) workDays);
                    sumConventionSalary = getDecimalNotNull(subAccount.getConventionSalary()).multiply(new BigDecimal(workDays).divide(new BigDecimal(days), 2, RoundingMode.HALF_UP));
                } else {
//                    model.setWorkDays(0);
                    continue;
                }
                //提成效益
                sumCommissionSalary = sumSaleSalary.multiply(getDecimalNotNull(subAccount.getCommissionRatio())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                model.setMonthSalary(sumSaleSalary);
                model.setBaseProfit(sumConventionSalary);
                model.setCommissionProfit(sumCommissionSalary);

                //查询加班效益
                QueryWrapper<YkfWorkOvertimeRecordEntity> workRecordQueryWrapper = new QueryWrapper<>();
                workRecordQueryWrapper.lambda().ge(YkfWorkOvertimeRecordEntity::getStartDate, startDate)
                        .le(YkfWorkOvertimeRecordEntity::getEndDate, endDate)
                        .eq(YkfWorkOvertimeRecordEntity::getUserId, userId);
                List<YkfWorkOvertimeRecordEntity> list3 = workOvertimeRecordService.list(workRecordQueryWrapper);

                BigDecimal sumWorkOverSalary = BigDecimal.ZERO;
                if (ObjectUtil.isNotEmpty(list3)) {
                    for (YkfWorkOvertimeRecordEntity recordEntity : list3) {
                        sumWorkOverSalary = sumWorkOverSalary.add(recordEntity.getOvertimeSalary());
                    }
                }
                //效益合计=底薪效益+提成效益+加班效益
                BigDecimal sumSalary = sumConventionSalary.add(sumCommissionSalary).add(sumWorkOverSalary);
                model.setSumProfit(sumSalary);
                //查询基数，系数
                if (ObjectUtil.isNotEmpty(subAccount)) {
                    QueryWrapper<YkfCustomPostCommissionEntity> postCommissionQueryWrapper = new QueryWrapper<>();
                    if (StrUtil.equals(subAccount.getCompanyNo(), "ALL")) {
                        postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, subAccount.getCompanyNo())
                                .eq(YkfCustomPostCommissionEntity::getCustomPostType, user.getCustomPostType())
                                .last("limit 1");
                    } else {
                        postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, subAccount.getCompanyNo())
                                .last("limit 1");
                    }
                    YkfCustomPostCommissionEntity postCommission = postCommissionService.getOne(postCommissionQueryWrapper);
                    if (ObjectUtil.isNotEmpty(postCommission)) {
                        //基数
                        BigDecimal base = postCommission.getBase();
                        model.setBase(base);
                        //系数
                        BigDecimal coefficient = postCommission.getCoefficient();
                        model.setCoefficient(coefficient);
                        //提成工资=（效益合计-基数）*系数
                        BigDecimal salary = (sumSalary.subtract(base)).multiply(coefficient).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                        model.setCommissionSalary(salary.compareTo(BigDecimal.ZERO) >= 0 ? salary : BigDecimal.ZERO);
                    }
                }
                resultList.add(model);
            }
        }
        return resultList;
    }


    /**
     * 提成核对表
     *
     * @param condition
     * @return
     */
    @Override
    public List<CommissionModel> sumCommissionCheckPage(YkfAccountInputRecordEntity condition) {
        List<CommissionModel> resultList = new ArrayList<>();
        String keyword = condition.getKeyword();
        String month = condition.getMonth();
        DateTime monthDate = DateUtil.parse(month, "yyyy-MM");
        QueryWrapper<YkfAccountInputRecordEntity> inputRecordQueryWrapper = new QueryWrapper<>();
        //计算月份首日日期和尾日日期
        DateTime startDate = DateUtil.beginOfMonth(monthDate);
        DateTime endDate = DateUtil.endOfMonth(monthDate);
        long days = DateUtil.betweenDay(startDate, endDate, true) + 1;
        QueryWrapper<YkfCustomerSubAccountEntity> subQueryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(keyword)) {
            //查询符合条件的用户
            QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().and(wrapper -> wrapper.like(SysUserEntity::getFlowerName, keyword)
                            .or().like(SysUserEntity::getName, keyword));
            List<SysUserEntity> list = sysUserService.list(queryWrapper);
            if (ObjectUtil.isNotEmpty(list)) {
                List<Long> userIds = list.stream().map(SysUserEntity::getUserId).collect(Collectors.toList());
                subQueryWrapper.lambda().and(wrapper -> wrapper.in(YkfCustomerSubAccountEntity::getUserId, userIds)
                        .or().like(YkfCustomerSubAccountEntity::getNo, keyword));
            } else {
                return new ArrayList<>();
            }
//            subQueryWrapper.lambda().and(wrapper -> wrapper.like(YkfCustomerSubAccountEntity::getFlowerName, keyword)
//                    .or().like(YkfCustomerSubAccountEntity::getName, keyword)
//                    .or().like(YkfCustomerSubAccountEntity::getNo, keyword));
        }
        if (StrUtil.isNotBlank(condition.getCompanyNo())) {
            subQueryWrapper.lambda().eq(YkfCustomerSubAccountEntity::getCompanyNo, condition.getCompanyNo());
        }
        subQueryWrapper.lambda().ge(YkfCustomerSubAccountEntity::getEndDate, startDate)
                .le(YkfCustomerSubAccountEntity::getStartDate, endDate);
        List<Long> powerSubAccountIds = sysUserService.getPowerSubAccountIds();
        if (ObjectUtil.isEmpty(powerSubAccountIds)) {
            return new ArrayList<>();
        } else {
            if (!powerSubAccountIds.contains(0L)) {
                subQueryWrapper.lambda().in(YkfCustomerSubAccountEntity::getSubAccountId, powerSubAccountIds);
            }
        }
        List<YkfCustomerSubAccountEntity> list4 = subAccountService.list(subQueryWrapper);
        boolean masterCompany = sysUserService.isMasterCompany();
        if (ObjectUtil.isNotEmpty(list4)) {
            //查询所有的数据记录
            List<Long> subAccountIds = list4.stream().map(YkfCustomerSubAccountEntity::getSubAccountId).distinct().collect(Collectors.toList());
            QueryWrapper<YkfAccountInputRecordEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(YkfAccountInputRecordEntity::getSubAccountId, subAccountIds)
                    .ge(YkfAccountInputRecordEntity::getDate, startDate)
                    .le(YkfAccountInputRecordEntity::getDate, endDate);
            List<YkfAccountInputRecordEntity> list5 = this.list(queryWrapper);
            Map<Long, List<YkfAccountInputRecordEntity>> map = new HashMap<>();
            if (ObjectUtil.isNotEmpty(list5)) {
                map = list5.stream().collect(Collectors.groupingBy(YkfAccountInputRecordEntity::getSubAccountId));
            }
            Map<String, List<YkfCustomerSubAccountEntity>> map2 = list4.stream().collect(Collectors.groupingBy(o -> StrUtil.toString(o.getUserId())));
            for (List<YkfCustomerSubAccountEntity> listValue : map2.values()) {
                CommissionModel model = new CommissionModel();
                model.setMonth(month);
                //总底薪收益
                BigDecimal sumConventionSalary = BigDecimal.ZERO;
                //总提成收益
                BigDecimal sumCommissionSalary = BigDecimal.ZERO;
                //总提成收益
                BigDecimal sumSaleSalary = BigDecimal.ZERO;
                YkfCustomerSubAccountEntity account = listValue.get(0);
                Long userId = account.getUserId();
                model.setBaseSalary(account.getConventionSalary());
                model.setExNameLabel(account.getExNameLabel());
                model.setShopName(account.getShopName());
                model.setAccountName(account.getAccountName());
                model.setStartDate(DateUtil.formatDate(account.getStartDate()));
                model.setEndDate(DateUtil.formatDate(account.getEndDate()));
                model.setCommissionRatio(account.getCommissionRatio());
                SysUserEntity user = sysUserService.getById(userId);
                if (ObjectUtil.isNotEmpty(user)) {
                    model.setCustomGroupName(user.getCustomGroupName());
                    model.setPestName(user.getPestName());
                    model.setOnDutyStatus(user.getOnDutyStatus());
                    model.setEntryDate(user.getEntryDate() != null ? DateUtil.formatDate(user.getEntryDate()) : "");
                    model.setBecomeRegularStatus(user.getBecomeRegularStatus());
                    model.setBecomeRegulardDate(user.getBecomeRegulardDate() != null ? DateUtil.formatDate(user.getBecomeRegulardDate()) : "");
                    model.setGroupNo(user.getGroupNo());
                    model.setNo(user.getNo());
                    model.setCompanyNo(user.getCompanyNo());
                    model.setCompanyName(user.getCompanyName());
                    model.setCustomPostType(user.getCustomPostType());
                    model.setCustomPostTypeName(user.getCustomPostTypeName());
                    model.setName(user.getName());
                    model.setFlowerName(user.getFlowerName());
                    model.setGroupNo(user.getGroupNo());
                    model.setNo(user.getNo());
                } else {
                    model.setName(account.getName());
                    model.setFlowerName(account.getFlowerName());
                    model.setGroupNo(account.getGroupNo());
                    model.setNo(account.getNo());
                }
                for (YkfCustomerSubAccountEntity subAccount : listValue) {
                    if (masterCompany) {
                        subAccount.setConventionSalary(subAccount.getCompanyBaseSalary());
                    }

                    //计算工作天数
                    Date start;
                    Date end;
                    if (startDate.compareTo(subAccount.getStartDate()) > 0) {
                        start = startDate;
                    } else {
                        start = subAccount.getStartDate();
                    }
                    if (endDate.compareTo(subAccount.getEndDate()) < 0) {
                        DateTime date = DateUtil.date();
                        if (date.compareTo(endDate) < 0) {
                            end = date;
                        } else {
                            end = endDate;
                        }
                    } else {
                        end = subAccount.getEndDate();
                    }
                    long workDays = DateUtil.betweenDay(start, end, false) + 1;

//                        model.setWorkDays((int) workDays);
                    sumConventionSalary = sumConventionSalary.add(getDecimalNotNull(subAccount.getConventionSalary()).multiply(new BigDecimal(workDays)).divide(new BigDecimal(days), 2, RoundingMode.HALF_UP));
//                    model.setWorkDays(list.size());
                    List<YkfAccountInputRecordEntity> list = map.get(subAccount.getSubAccountId());
                    BigDecimal sumAccountSalary = BigDecimal.ZERO;
                    if (ObjectUtil.isNotEmpty(list) && !list.isEmpty()) {
                        for (YkfAccountInputRecordEntity record : list) {
                            sumSaleSalary = sumSaleSalary.add(getDecimalNotNull(record.getSalesRevenue()));
                            sumAccountSalary = sumAccountSalary.add(getDecimalNotNull(record.getSalesRevenue()));
                        }
                    }
                    //提成效益
                    sumCommissionSalary = sumCommissionSalary.add(sumAccountSalary.multiply(getDecimalNotNull(subAccount.getCommissionRatio())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
                }

                model.setMonthSalary(sumSaleSalary);
                model.setBaseProfit(sumConventionSalary);
                model.setCommissionProfit(sumCommissionSalary);

                //查询加班效益
                QueryWrapper<YkfWorkOvertimeRecordEntity> workRecordQueryWrapper = new QueryWrapper<>();
                workRecordQueryWrapper.lambda().ge(YkfWorkOvertimeRecordEntity::getStartDate, startDate)
                        .le(YkfWorkOvertimeRecordEntity::getEndDate, endDate)
                        .eq(YkfWorkOvertimeRecordEntity::getUserId, userId);
                List<YkfWorkOvertimeRecordEntity> list3 = workOvertimeRecordService.list(workRecordQueryWrapper);

                BigDecimal sumWorkOverSalary = BigDecimal.ZERO;
                if (ObjectUtil.isNotEmpty(list3)) {
                    for (YkfWorkOvertimeRecordEntity recordEntity : list3) {
                        sumWorkOverSalary = sumWorkOverSalary.add(recordEntity.getOvertimeSalary());
                    }
                }
                //效益合计=底薪效益+提成效益+加班效益
                BigDecimal sumSalary = sumConventionSalary.add(sumCommissionSalary).add(sumWorkOverSalary);
                model.setSumProfit(sumSalary);
                //查询基数，系数
                SysUserEntity user1 = sysUserService.getById(listValue.get(0).getUserId());
                if (ObjectUtil.isNotEmpty(user1)) {
                    QueryWrapper<YkfCustomPostCommissionEntity> postCommissionQueryWrapper = new QueryWrapper<>();
                    if (StrUtil.equals(account.getCompanyNo(), "ALL")) {
                        postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, account.getCompanyNo())
                                .eq(YkfCustomPostCommissionEntity::getCustomPostType, user1.getCustomPostType())
                                .last("limit 1");
                    } else {
                        postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, account.getCompanyNo())
                                .last("limit 1");
                    }
                    YkfCustomPostCommissionEntity postCommission = postCommissionService.getOne(postCommissionQueryWrapper);
                    if (ObjectUtil.isNotEmpty(postCommission)) {
                        //基数
                        BigDecimal base = postCommission.getBase();
                        model.setBase(base);
                        //系数
                        BigDecimal coefficient = postCommission.getCoefficient();
                        model.setCoefficient(coefficient);
                        //提成工资=（效益合计-基数）*系数
                        BigDecimal salary = (sumSalary.subtract(base)).multiply(coefficient).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                        model.setCommissionSalary(salary.compareTo(BigDecimal.ZERO) >= 0 ? salary : BigDecimal.ZERO);
                    }
                }
                resultList.add(model);
            }
        }
        return resultList;
    }

    @Override
    public CommissionModel commissionCheckPage(Long userId) {
        CommissionModel result = new CommissionModel();
        //计算月份首日日期和尾日日期
        DateTime date1 = DateUtil.date();
        DateTime startDate = DateUtil.beginOfMonth(date1);
        DateTime endDate = DateUtil.endOfMonth(date1);
        long days = DateUtil.betweenDay(startDate, endDate, true) + 1;
        QueryWrapper<YkfCustomerSubAccountEntity> subQueryWrapper = new QueryWrapper<>();
        subQueryWrapper.lambda().eq(YkfCustomerSubAccountEntity::getUserId, userId);
        subQueryWrapper.lambda().ge(YkfCustomerSubAccountEntity::getEndDate, startDate)
                .le(YkfCustomerSubAccountEntity::getStartDate, endDate);
        List<Long> powerSubAccountIds = sysUserService.getPowerSubAccountIds();
        if (ObjectUtil.isEmpty(powerSubAccountIds)) {
            return result;
        } else {
            if (!powerSubAccountIds.contains(0L)) {
                subQueryWrapper.lambda().in(YkfCustomerSubAccountEntity::getSubAccountId, powerSubAccountIds);
            }
        }
        List<YkfCustomerSubAccountEntity> listValue = subAccountService.list(subQueryWrapper);
        boolean masterCompany = sysUserService.isMasterCompany();
        if (ObjectUtil.isNotEmpty(listValue)) {
            //查询所有的数据记录
            List<Long> subAccountIds = listValue.stream().map(YkfCustomerSubAccountEntity::getSubAccountId).distinct().collect(Collectors.toList());
            QueryWrapper<YkfAccountInputRecordEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(YkfAccountInputRecordEntity::getSubAccountId, subAccountIds)
                    .ge(YkfAccountInputRecordEntity::getDate, startDate)
                    .le(YkfAccountInputRecordEntity::getDate, endDate);
            List<YkfAccountInputRecordEntity> list5 = this.list(queryWrapper);
            Map<Long, List<YkfAccountInputRecordEntity>> map = new HashMap<>();
            if (ObjectUtil.isNotEmpty(list5)) {
                map = list5.stream().collect(Collectors.groupingBy(YkfAccountInputRecordEntity::getSubAccountId));
            }
            CommissionModel model = new CommissionModel();
            //总底薪收益
            BigDecimal sumConventionSalary = BigDecimal.ZERO;
            //总提成收益
            BigDecimal sumCommissionSalary = BigDecimal.ZERO;
            //总提成收益
            BigDecimal sumSaleSalary = BigDecimal.ZERO;
            YkfCustomerSubAccountEntity account = listValue.get(0);
            model.setBaseSalary(account.getConventionSalary());
            model.setExNameLabel(account.getExNameLabel());
            model.setShopName(account.getShopName());
            model.setAccountName(account.getAccountName());
            model.setStartDate(DateUtil.formatDate(account.getStartDate()));
            model.setEndDate(DateUtil.formatDate(account.getEndDate()));
            model.setCommissionRatio(account.getCommissionRatio());
            model.setName(account.getName());
            model.setFlowerName(account.getFlowerName());
            model.setGroupNo(account.getGroupNo());
            model.setNo(account.getNo());
            SysUserEntity user = sysUserService.getById(userId);
            if (ObjectUtil.isNotEmpty(user)) {
                model.setCustomGroupName(user.getCustomGroupName());
                model.setPestName(user.getPestName());
                model.setOnDutyStatus(user.getOnDutyStatus());
                model.setEntryDate(user.getEntryDate() != null ? DateUtil.formatDate(user.getEntryDate()) : "");
                model.setBecomeRegularStatus(user.getBecomeRegularStatus());
                model.setBecomeRegulardDate(user.getBecomeRegulardDate() != null ? DateUtil.formatDate(user.getBecomeRegulardDate()) : "");
                model.setGroupNo(user.getGroupNo());
                model.setNo(user.getNo());
            }
            for (YkfCustomerSubAccountEntity subAccount : listValue) {
                if (masterCompany) {
                    subAccount.setConventionSalary(subAccount.getCompanyBaseSalary());
                }

                List<YkfAccountInputRecordEntity> list = map.get(subAccount.getSubAccountId());
                if (ObjectUtil.isNotEmpty(list) && !list.isEmpty()) {
                    for (YkfAccountInputRecordEntity record : list) {
                        sumSaleSalary = sumSaleSalary.add(getDecimalNotNull(record.getSalesRevenue()));
                    }
                    //计算工作天数
                    Date start;
                    Date end;
                    if (startDate.compareTo(subAccount.getStartDate()) > 0) {
                        start = startDate;
                    } else {
                        start = subAccount.getStartDate();
                    }
                    if (endDate.compareTo(subAccount.getEndDate()) < 0) {
                        DateTime date = DateUtil.date();
                        if (date.compareTo(endDate) < 0) {
                            end = date;
                        } else {
                            end = endDate;
                        }
                    } else {
                        end = subAccount.getEndDate();
                    }
                    long workDays = DateUtil.betweenDay(start, end, false) + 1;

//                        model.setWorkDays((int) workDays);
                    sumConventionSalary = sumConventionSalary.add(getDecimalNotNull(subAccount.getConventionSalary()).multiply(new BigDecimal(workDays).divide(new BigDecimal(days), 2, RoundingMode.HALF_UP)));
//                    model.setWorkDays(list.size());
                    //提成效益
                    sumCommissionSalary = sumCommissionSalary.add(sumSaleSalary.multiply(getDecimalNotNull(subAccount.getCommissionRatio())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
                }
            }

            model.setMonthSalary(sumSaleSalary);
            model.setBaseProfit(sumConventionSalary);
            model.setCommissionProfit(sumCommissionSalary);

            //查询加班效益
            QueryWrapper<YkfWorkOvertimeRecordEntity> workRecordQueryWrapper = new QueryWrapper<>();
            workRecordQueryWrapper.lambda().ge(YkfWorkOvertimeRecordEntity::getStartDate, startDate)
                    .le(YkfWorkOvertimeRecordEntity::getEndDate, endDate)
                    .eq(YkfWorkOvertimeRecordEntity::getUserId, userId);
            List<YkfWorkOvertimeRecordEntity> list3 = workOvertimeRecordService.list(workRecordQueryWrapper);

            BigDecimal sumWorkOverSalary = BigDecimal.ZERO;
            if (ObjectUtil.isNotEmpty(list3)) {
                for (YkfWorkOvertimeRecordEntity recordEntity : list3) {
                    sumWorkOverSalary = sumWorkOverSalary.add(recordEntity.getOvertimeSalary());
                }
            }
            //效益合计=底薪效益+提成效益+加班效益
            BigDecimal sumSalary = sumConventionSalary.add(sumCommissionSalary).add(sumWorkOverSalary);
            model.setSumProfit(sumSalary);
            //查询基数，系数
            SysUserEntity user1 = sysUserService.getById(listValue.get(0).getUserId());
            if (ObjectUtil.isNotEmpty(user1)) {
                QueryWrapper<YkfCustomPostCommissionEntity> postCommissionQueryWrapper = new QueryWrapper<>();
                if (StrUtil.equals(account.getCompanyNo(), "ALL")) {
                    postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, account.getCompanyNo())
                            .eq(YkfCustomPostCommissionEntity::getCustomPostType, user1.getCustomPostType())
                            .last("limit 1");
                } else {
                    postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, account.getCompanyNo())
                            .last("limit 1");
                }
                YkfCustomPostCommissionEntity postCommission = postCommissionService.getOne(postCommissionQueryWrapper);
                if (ObjectUtil.isNotEmpty(postCommission)) {
                    //基数
                    BigDecimal base = postCommission.getBase();
                    model.setBase(base);
                    //系数
                    BigDecimal coefficient = postCommission.getCoefficient();
                    model.setCoefficient(coefficient);
                    //提成工资=（效益合计-基数）*系数
                    BigDecimal salary = (sumSalary.subtract(base)).multiply(coefficient).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                    model.setCommissionSalary(salary.compareTo(BigDecimal.ZERO) >= 0 ? salary : BigDecimal.ZERO);
                }
            }
            return model;
        }
        return result;
    }

    /**
     * 提成核对表
     *
     * @param condition
     * @return
     */
    public List<CommissionModel> sumCommissionCheckPage2(YkfAccountInputRecordEntity condition) {
        String keyword = condition.getKeyword();
        String month = condition.getMonth();
        DateTime monthDate = DateUtil.parse(month, "yyyy-MM");
        QueryWrapper<YkfAccountInputRecordEntity> inputRecordQueryWrapper = new QueryWrapper<>();
        //计算月份首日日期和尾日日期
        DateTime startDate = DateUtil.beginOfMonth(monthDate);
        DateTime endDate = DateUtil.endOfMonth(monthDate);
        long days = DateUtil.betweenDay(startDate, endDate, true) + 1;
        QueryWrapper<YkfCustomerSubAccountEntity> subQueryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(keyword)) {
            subQueryWrapper.lambda().and(wrapper -> wrapper.like(YkfCustomerSubAccountEntity::getFlowerName, keyword)
                            .or().like(YkfCustomerSubAccountEntity::getName, keyword))
                    .like(YkfCustomerSubAccountEntity::getNo, keyword);
        }
        List<YkfCustomerSubAccountEntity> list4 = subAccountService.list(subQueryWrapper);
        if (ObjectUtil.isEmpty(list4)) {
            return new ArrayList<>();
        }
        List<Long> subAccountIds = list4.stream().map(YkfCustomerSubAccountEntity::getSubAccountId).collect(Collectors.toList());
        inputRecordQueryWrapper.lambda().in(YkfAccountInputRecordEntity::getSubAccountId, subAccountIds)
                .ge(YkfAccountInputRecordEntity::getDate, startDate)
                .le(YkfAccountInputRecordEntity::getDate, endDate);
        List<YkfAccountInputRecordEntity> list = this.list(inputRecordQueryWrapper);
        List<CommissionModel> resultList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(list)) {
            Map<Long, List<YkfAccountInputRecordEntity>> collect = list.stream().collect(Collectors.groupingBy(YkfAccountInputRecordEntity::getSubAccountId));
            List<Long> subIds = new ArrayList<>(collect.keySet());

            //查询底薪提成记录
            QueryWrapper<YkfSubAccountRecordEntity> subAccountRecordQueryWrapper = new QueryWrapper<>();
            subAccountRecordQueryWrapper.lambda().le(YkfSubAccountRecordEntity::getCreateTime, endDate)
                    .in(YkfSubAccountRecordEntity::getSubAccountId, subIds)
                    .orderByAsc(YkfSubAccountRecordEntity::getCreateTime);
            List<YkfSubAccountRecordEntity> list1 = subAccountRecordService.list(subAccountRecordQueryWrapper);
            Map<String, List<YkfSubAccountRecordEntity>> collect1 = list1.stream().collect(Collectors.groupingBy(o -> DateUtil.formatDate(o.getCreateTime())));
            List<String> dateList = collect1.keySet().stream().sorted().collect(Collectors.toList());
            //分段计算提成
            for (Long subId : subIds) {
                CommissionModel model = new CommissionModel();
                //总底薪收益
                BigDecimal sumConventionSalary = BigDecimal.ZERO;
                //总提成收益
                BigDecimal sumCommissionSalary = BigDecimal.ZERO;
                //总提成收益
                BigDecimal sumSaleSalary = BigDecimal.ZERO;
                YkfCustomerSubAccountEntity subAccount = subAccountService.getById(subId);
                List<YkfAccountInputRecordEntity> list2 = collect.get(subId);

                Long userId = subAccount.getUserId();
                SysUserEntity user = sysUserService.getById(userId);
                for (YkfAccountInputRecordEntity record : list2) {
                    //匹配并计算提成,查询加班效益
                    Map<String, BigDecimal> map = countCommission(record, dateList, collect1, days);
                    sumConventionSalary = sumConventionSalary.add(map.get("conventionSalary"));
                    sumCommissionSalary = sumCommissionSalary.add(map.get("commissionSalary"));
                    sumSaleSalary = sumSaleSalary.add(record.getSalesRevenue());
                }
                if (ObjectUtil.isNotEmpty(subAccount)) {
                    model.setBaseSalary(subAccount.getConventionSalary());
                    model.setExNameLabel(subAccount.getExNameLabel());
                    model.setShopName(subAccount.getShopName());
                    model.setAccountName(subAccount.getAccountName());
                    model.setStartDate(DateUtil.formatDate(subAccount.getStartDate()));
                    model.setEndDate(DateUtil.formatDate(subAccount.getEndDate()));
                    model.setCommissionRatio(subAccount.getCommissionRatio());
                    model.setName(subAccount.getName());
                    model.setFlowerName(subAccount.getFlowerName());
                    model.setGroupNo(subAccount.getGroupNo());
                    model.setNo(subAccount.getNo());
                }
                if (ObjectUtil.isNotEmpty(user)) {
                    model.setCustomGroupName(user.getCustomGroupName());
                    model.setPestName(user.getPestName());
                    model.setOnDutyStatus(user.getOnDutyStatus());
                    model.setEntryDate(user.getEntryDate() != null ? DateUtil.formatDate(user.getEntryDate()) : "");
                    model.setBecomeRegularStatus(user.getBecomeRegularStatus());
                    model.setBecomeRegulardDate(user.getBecomeRegulardDate() != null ? DateUtil.formatDate(user.getBecomeRegulardDate()) : "");
                }

                model.setWorkDays(list2.size());
                model.setMonthSalary(sumSaleSalary);
                model.setBaseProfit(sumConventionSalary);
                model.setCommissionProfit(sumCommissionSalary);

                //查询加班效益
                QueryWrapper<YkfWorkOvertimeRecordEntity> workRecordQueryWrapper = new QueryWrapper<>();
                workRecordQueryWrapper.lambda().ge(YkfWorkOvertimeRecordEntity::getStartDate, startDate)
                        .le(YkfWorkOvertimeRecordEntity::getEndDate, endDate)
                        .eq(YkfWorkOvertimeRecordEntity::getUserId, userId);
                List<YkfWorkOvertimeRecordEntity> list3 = workOvertimeRecordService.list(workRecordQueryWrapper);

                BigDecimal sumWorkOverSalary = BigDecimal.ZERO;
                if (ObjectUtil.isNotEmpty(list3)) {
                    for (YkfWorkOvertimeRecordEntity recordEntity : list3) {
                        sumWorkOverSalary = sumWorkOverSalary.add(recordEntity.getOvertimeSalary());
                    }
                }
                //效益合计=底薪效益+提成效益+加班效益
                BigDecimal sumSalary = sumConventionSalary.add(sumCommissionSalary).add(sumWorkOverSalary);
                model.setSumProfit(sumSalary);
                //查询基数，系数
                if (ObjectUtil.isNotEmpty(subAccount)) {
                    QueryWrapper<YkfCustomPostCommissionEntity> postCommissionQueryWrapper = new QueryWrapper<>();
                    if (StrUtil.equals(subAccount.getCompanyNo(), "ALL")) {
                        postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, subAccount.getCompanyNo())
                                .eq(YkfCustomPostCommissionEntity::getCustomPostType, user.getCustomPostType())
                                .last("limit 1");
                    } else {
                        postCommissionQueryWrapper.lambda().eq(YkfCustomPostCommissionEntity::getCompanyNo, subAccount.getCompanyNo())
                                .last("limit 1");
                    }
                    YkfCustomPostCommissionEntity postCommission = postCommissionService.getOne(postCommissionQueryWrapper);
                    if (ObjectUtil.isNotEmpty(postCommission)) {
                        //基数
                        BigDecimal base = postCommission.getBase();
                        model.setBase(base);
                        //系数
                        BigDecimal coefficient = postCommission.getCoefficient();
                        model.setCoefficient(coefficient);
                        //提成工资=（效益合计-基数）*系数
                        BigDecimal salary = (sumSalary.subtract(base)).multiply(coefficient).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                        model.setCommissionSalary(salary.compareTo(BigDecimal.ZERO) >= 0 ? salary : BigDecimal.ZERO);
                    }
                }
                resultList.add(model);
            }
        }
        return resultList;
    }

    @Override
    public List<ServiceDataModel> serviceData(ServiceDataModel serviceData) {
        if (ObjectUtil.isEmpty(serviceData) || StrUtil.isBlank(serviceData.getStartMonth()) || StrUtil.isBlank(serviceData.getEndMonth())) {
            throw new RRException("参数缺失");
        }
        DateTime startMonth = DateUtil.parse(serviceData.getStartMonth(), "yyyy-MM");
        DateTime endMonth = DateUtil.parse(serviceData.getEndMonth(), "yyyy-MM");
        DateTime startDate = DateUtil.beginOfMonth(startMonth);
        DateTime endDate = DateUtil.endOfMonth(endMonth);
        List<ServiceDataModel> resultList = new ArrayList<>();
        QueryWrapper<YkfAccountInputRecordEntity> queryWrapper = new QueryWrapper<>();
        List<Long> powerSubAccountIds = sysUserService.getPowerSubAccountIds();
        if (ObjectUtil.isEmpty(powerSubAccountIds)) {
            return new ArrayList<>();
        } else {
            if (!powerSubAccountIds.contains(0L)) {
                queryWrapper.lambda().in(YkfAccountInputRecordEntity::getSubAccountId, powerSubAccountIds);
            }
        }
//        queryWrapper.lambda().ge(YkfAccountInputRecordEntity::getDate, startDate)
//                .le(YkfAccountInputRecordEntity::getDate, endDate)
//                .orderByDesc(YkfAccountInputRecordEntity::getDate);
//        List<YkfAccountInputRecordEntity> list = this.list(queryWrapper);
//        Map<String, List<YkfAccountInputRecordEntity>> collect = new HashMap<>();
//        if (ObjectUtil.isNotEmpty(list)) {
//            collect = list.stream().collect(Collectors.groupingBy(o -> DateUtil.format(o.getDate(), "yyyy-MM")));
//        }
        while (startMonth.compareTo(endMonth) <= 0) {
            String month = DateUtil.format(startMonth, "yyyy-MM");
//            List<YkfAccountInputRecordEntity> list1 = collect.get(month);
            ServiceDataModel serviceDataModel = new ServiceDataModel();
            BigDecimal value = BigDecimal.ZERO;
//            if (ObjectUtil.isNotEmpty(list1)) {
//                for (YkfAccountInputRecordEntity item : list1) {
//                    value = value.add(item.getSalesRevenue());
//                }
//            }
            YkfAccountInputRecordEntity condition = new YkfAccountInputRecordEntity();
            condition.setMonth(month);
            List<CommissionModel> commissionList = sumCommissionCheckPage(condition);
            if (ObjectUtil.isNotEmpty(commissionList)) {
                for (CommissionModel model : commissionList) {
                    value = value.add(ObjectUtil.isEmpty(model.getSumProfit()) ? BigDecimal.ZERO : model.getSumProfit());
                }
            }
            serviceDataModel.setMonth(month);
            serviceDataModel.setValue(value);
            resultList.add(serviceDataModel);
            startMonth = DateUtil.offsetMonth(startMonth, 1);
        }
        return resultList;
    }


    public List<ServiceChargeExcel> serviceExcelData(ExcelReq req) {
        if (ObjectUtil.isEmpty(req) || StrUtil.isBlank(req.getStartMonth()) || StrUtil.isBlank(req.getEndMonth())) {
            return new ArrayList<>();
        }
        DateTime startMonth = DateUtil.parse(req.getStartMonth(), "yyyy-MM");
        DateTime endMonth = DateUtil.parse(req.getEndMonth(), "yyyy-MM");
        DateTime startDate = DateUtil.beginOfMonth(startMonth);
        DateTime endDate = DateUtil.endOfMonth(endMonth);
        List<ServiceChargeExcel> resultList = new ArrayList<>();
//        QueryWrapper<YkfAccountInputRecordEntity> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().ge(YkfAccountInputRecordEntity::getDate, startDate)
//                .le(YkfAccountInputRecordEntity::getDate, endDate)
//                .orderByDesc(YkfAccountInputRecordEntity::getDate);
//        List<YkfAccountInputRecordEntity> list = this.list(queryWrapper);
//        if (ObjectUtil.isNotEmpty(list)) {
//            Map<String, List<YkfAccountInputRecordEntity>> collect = list.stream().collect(Collectors.groupingBy(o -> DateUtil.format(o.getDate(), "yyyy-MM")));
//            while (startMonth.compareTo(endMonth) <= 0) {
//                String month = DateUtil.format(startMonth, "yyyy-MM");
//                List<YkfAccountInputRecordEntity> list1 = collect.get(month);
//                ServiceChargeExcel excelModel = new ServiceChargeExcel();
//                BigDecimal value = BigDecimal.ZERO;
//                if (ObjectUtil.isNotEmpty(list1)) {
//                    for (YkfAccountInputRecordEntity item : list1) {
//                        value = value.add(item.getSalesRevenue());
//                    }
//                }
//                excelModel.setMonth(month);
//                excelModel.setValue(value);
//                resultList.add(excelModel);
//                startMonth = DateUtil.offsetMonth(startMonth, 1);
//            }
//        }

        while (startMonth.compareTo(endMonth) <= 0) {
            String month = DateUtil.format(startMonth, "yyyy-MM");
//            List<YkfAccountInputRecordEntity> list1 = collect.get(month);
            ServiceChargeExcel serviceDataModel = new ServiceChargeExcel();
            BigDecimal value = BigDecimal.ZERO;
//            if (ObjectUtil.isNotEmpty(list1)) {
//                for (YkfAccountInputRecordEntity item : list1) {
//                    value = value.add(item.getSalesRevenue());
//                }
//            }
            YkfAccountInputRecordEntity condition = new YkfAccountInputRecordEntity();
            condition.setMonth(month);
            List<CommissionModel> commissionList = sumCommissionCheckPage(condition);
            if (ObjectUtil.isNotEmpty(commissionList)) {
                for (CommissionModel model : commissionList) {
                    value = value.add(ObjectUtil.isEmpty(model.getSumProfit()) ? BigDecimal.ZERO : model.getSumProfit());
                }
            }
            serviceDataModel.setMonth(month);
            serviceDataModel.setValue(value);
            resultList.add(serviceDataModel);
            startMonth = DateUtil.offsetMonth(startMonth, 1);
        }
        return resultList;
    }

    @Override
    public void dataQueryInput(ExcelReq req, HttpServletResponse response) throws IOException {
        //查询列表
        ParamsModel<YkfAccountInputRecordEntity> params = new ParamsModel<>();
        params.setCondition(req.getCondition(new TypeReference<YkfAccountInputRecordEntity>() {
        }));
        params.setSort(req.getSort());
        ParamsModel.PageParams pageParams = new ParamsModel.PageParams();
        pageParams.setIndex(1L);
        pageParams.setSize(9999L);
        params.setPage(pageParams);
        PageUtils pageUtils = toBeEnteredPage(params);
        //查询列表
        List<YkfAccountInputRecordEntity> beEnteredList = (List<YkfAccountInputRecordEntity>) pageUtils.getList();
        List<AccountInputRecordExcel> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(beEnteredList)) {
            for (YkfAccountInputRecordEntity record : beEnteredList) {
                AccountInputRecordExcel excel = new AccountInputRecordExcel();
                BeanUtil.copyProperties(record, excel);
                list.add(excel);
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("数据录入记录", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), AccountInputRecordExcel.class)
                .sheet("数据录入记录")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
                .doWrite(list);
    }

    /**
     * 店铺每日绩效
     */
    @Override
    public void dataQueryAnalysis1(ExcelReq req, HttpServletResponse response) throws IOException {
        //查询列表
        ParamsModel<YkfAccountInputRecordEntity> params = new ParamsModel<>();
        params.setCondition(req.getCondition(new TypeReference<YkfAccountInputRecordEntity>() {
        }));
        params.setSort(req.getSort());
        ParamsModel.PageParams pageParams = new ParamsModel.PageParams();
        pageParams.setIndex(1L);
        pageParams.setSize(9999L);
        params.setPage(pageParams);
        PageUtils pageUtils = dayPage(params);
        List<YkfAccountInputRecordEntity> dataList = (List<YkfAccountInputRecordEntity>) pageUtils.getList();
        List<DataQueryAnalysis1Excel> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dataList)) {
            for (YkfAccountInputRecordEntity item : dataList) {
                DataQueryAnalysis1Excel excel = new DataQueryAnalysis1Excel();
                BeanUtil.copyProperties(item, excel);
                list.add(excel);
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("店铺每日绩效", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), DataQueryAnalysis1Excel.class)
                .sheet("店铺每日绩效")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
                .doWrite(list);
    }

    /**
     * 店铺整体绩效
     */
    @Override
    public void dataQueryAnalysis2(ExcelReq req, HttpServletResponse response) throws IOException {
        //查询列表
        ParamsModel<YkfAccountInputRecordEntity> params = new ParamsModel<>();
        params.setCondition(req.getCondition(new TypeReference<YkfAccountInputRecordEntity>() {
        }));
        params.setSort(req.getSort());
        ParamsModel.PageParams pageParams = new ParamsModel.PageParams();
        pageParams.setIndex(1L);
        pageParams.setSize(9999L);
        params.setPage(pageParams);
        PageUtils pageUtils = overallPage(params);
        List<YkfAccountInputRecordEntity> dataList = (List<YkfAccountInputRecordEntity>) pageUtils.getList();
        List<DataQueryAnalysis2Excel> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dataList)) {
            for (YkfAccountInputRecordEntity item : dataList) {
                DataQueryAnalysis2Excel excel = new DataQueryAnalysis2Excel();
                BeanUtil.copyProperties(item, excel);
                list.add(excel);
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("店铺整体绩效", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), DataQueryAnalysis2Excel.class)
                .sheet("店铺整体绩效")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
                .doWrite(list);

    }

    /**
     * 店铺整体绩效
     */
    @Override
    public void dataQueryAnalysis2Detail(ExcelReq req, HttpServletResponse response) throws IOException {
        //查询列表
        ParamsModel<YkfAccountInputRecordEntity> params = new ParamsModel<>();
        params.setCondition(req.getCondition(new TypeReference<YkfAccountInputRecordEntity>() {
        }));
        params.setSort(req.getSort());
        ParamsModel.PageParams pageParams = new ParamsModel.PageParams();
        pageParams.setIndex(1L);
        pageParams.setSize(9999L);
        params.setPage(pageParams);
        PageUtils pageUtils = overallPage(params);
        List<YkfAccountInputRecordEntity> dataList = (List<YkfAccountInputRecordEntity>) pageUtils.getList();
        List<DataQueryAnalysis2DetailExcel> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dataList)) {
            for (YkfAccountInputRecordEntity item : dataList) {
                DataQueryAnalysis2DetailExcel excel = new DataQueryAnalysis2DetailExcel();
                BeanUtil.copyProperties(item, excel);
                list.add(excel);
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("店铺整体绩效详情", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), DataQueryAnalysis2DetailExcel.class)
                .sheet("店铺整体绩效详情")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
                .doWrite(list);

    }

    /**
     * 接待量预警
     *
     * @param req
     * @param response
     */
    @Override
    public void dataQueryAnalysis3(ExcelReq req, HttpServletResponse response) throws IOException {
        //查询列表
        ParamsModel<YkfAccountInputRecordEntity> params = new ParamsModel<>();
        params.setCondition(req.getCondition(new TypeReference<YkfAccountInputRecordEntity>() {
        }));
        params.setSort(req.getSort());
        ParamsModel.PageParams pageParams = new ParamsModel.PageParams();
        pageParams.setIndex(1L);
        pageParams.setSize(9999L);
        params.setPage(pageParams);
        PageUtils pageUtils = this.warningPage(params);
        List<YkfAccountInputRecordEntity> dataList = (List<YkfAccountInputRecordEntity>) pageUtils.getList();
        List<DataQueryAnalysis3Excel> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dataList)) {
            for (YkfAccountInputRecordEntity item : dataList) {
                DataQueryAnalysis3Excel excel = new DataQueryAnalysis3Excel();
                BeanUtil.copyProperties(item, excel);
                list.add(excel);
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("接待量预警", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), DataQueryAnalysis3Excel.class)
                .sheet("接待量预警")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
                .doWrite(list);

    }

    /**
     * 客服接待汇总表
     *
     * @param req
     * @param response
     */
    @Override
    public void dataQueryAnalysis4(ExcelReq req, HttpServletResponse response) throws IOException {
        //查询列表
        ParamsModel<YkfAccountInputRecordEntity> params = new ParamsModel<>();
        params.setCondition(req.getCondition(new TypeReference<YkfAccountInputRecordEntity>() {
        }));
        params.setSort(req.getSort());
        ParamsModel.PageParams pageParams = new ParamsModel.PageParams();
        pageParams.setIndex(1L);
        pageParams.setSize(9999L);
        params.setPage(pageParams);
        PageUtils pageUtils = this.customerDataPage(params);
        List<YkfAccountInputRecordEntity> dataList = (List<YkfAccountInputRecordEntity>) pageUtils.getList();
        List<DataQueryAnalysis4Excel> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dataList)) {
            for (YkfAccountInputRecordEntity item : dataList) {
                DataQueryAnalysis4Excel excel = new DataQueryAnalysis4Excel();
                BeanUtil.copyProperties(item, excel);
                list.add(excel);
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("客服接待汇总", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), DataQueryAnalysis4Excel.class)
                .sheet("客服接待汇总")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
                .doWrite(list);

    }


    /**
     * 客服接待汇总表
     *
     * @param req
     * @param response
     */
    @Override
    public void dataQueryAnalysis4Detail(ExcelReq req, HttpServletResponse response) throws IOException {
        //查询列表
        ParamsModel<YkfAccountInputRecordEntity> params = new ParamsModel<>();
        params.setCondition(req.getCondition(new TypeReference<YkfAccountInputRecordEntity>() {
        }));
        params.setSort(req.getSort());
        ParamsModel.PageParams pageParams = new ParamsModel.PageParams();
        pageParams.setIndex(1L);
        pageParams.setSize(9999L);
        params.setPage(pageParams);
        PageUtils pageUtils = this.customerDataPage(params);
        List<YkfAccountInputRecordEntity> dataList = (List<YkfAccountInputRecordEntity>) pageUtils.getList();
        List<DataQueryAnalysis4DetailExcel> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dataList)) {
            for (YkfAccountInputRecordEntity item : dataList) {
                DataQueryAnalysis4DetailExcel excel = new DataQueryAnalysis4DetailExcel();
                BeanUtil.copyProperties(item, excel);
                list.add(excel);
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("客服接待汇总详情", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), DataQueryAnalysis4DetailExcel.class)
                .sheet("客服接待汇总详情")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
                .doWrite(list);

    }

    /**
     * 客服考核汇总表
     *
     * @param req
     * @param response
     */
    @Override
    public void dataQueryAnalysis5(ExcelReq req, HttpServletResponse response) throws IOException {
        //查询列表
        ParamsModel<YkfAccountInputRecordEntity> params = new ParamsModel<>();
        params.setCondition(req.getCondition(new TypeReference<YkfAccountInputRecordEntity>() {
        }));
        params.setSort(req.getSort());
        ParamsModel.PageParams pageParams = new ParamsModel.PageParams();
        pageParams.setIndex(1L);
        pageParams.setSize(9999L);
        params.setPage(pageParams);
        PageUtils pageUtils = this.sumCustomerPage(params);
        List<YkfAccountInputRecordEntity> list = (List<YkfAccountInputRecordEntity>) pageUtils.getList();
        List<DataQueryAnalysis5Excel> excellist = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(list)) {
            for (YkfAccountInputRecordEntity recordEntity : list) {
                DataQueryAnalysis5Excel excel = new DataQueryAnalysis5Excel();
                BeanUtil.copyProperties(recordEntity, excel);
                excellist.add(excel);
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("客服接待汇总", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), DataQueryAnalysis5Excel.class)
                .sheet("客服接待汇总")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
                .doWrite(excellist);
    }


    /**
     * 客服考核汇总表
     *
     * @param req
     * @param response
     */
    @Override
    public void dataQueryAnalysis5Detail(ExcelReq req, HttpServletResponse response) throws IOException {
        //查询列表
        ParamsModel<YkfAccountInputRecordEntity> params = new ParamsModel<>();
        params.setCondition(req.getCondition(new TypeReference<YkfAccountInputRecordEntity>() {
        }));
        params.setSort(req.getSort());
        ParamsModel.PageParams pageParams = new ParamsModel.PageParams();
        pageParams.setIndex(1L);
        pageParams.setSize(9999L);
        params.setPage(pageParams);
        PageUtils pageUtils = this.sumCustomerPage(params);
        List<YkfAccountInputRecordEntity> list = (List<YkfAccountInputRecordEntity>) pageUtils.getList();
        List<DataQueryAnalysis5DetailExcel> excellist = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(list)) {
            for (YkfAccountInputRecordEntity recordEntity : list) {
                DataQueryAnalysis5DetailExcel excel = new DataQueryAnalysis5DetailExcel();
                BeanUtil.copyProperties(recordEntity, excel);
                excellist.add(excel);
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("客服接待汇总", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), DataQueryAnalysis5DetailExcel.class)
                .sheet("客服接待汇总")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
                .doWrite(excellist);
    }

    /**
     * personalCustomerDataPage
     *
     * @param req
     * @param response
     */
    @Override
    public void personal1(ExcelReq req, HttpServletResponse response) throws IOException {
        if (ObjectUtil.isNotEmpty(req)
                && ObjectUtil.isNotEmpty(req)
                && ObjectUtil.isNotEmpty(req.getDateStart())
                && ObjectUtil.isNotEmpty(req.getDateEnd())) {
            List<YkfAccountInputRecordEntity> dataList = baseMapper.personalCustomerDataList(CommonUtils.getUserId(), req.getDateStart(), req.getDateEnd());
            List<Personal1Excel> list = new ArrayList<>();
            if (ObjectUtil.isNotEmpty(dataList)) {
                for (YkfAccountInputRecordEntity record : dataList) {
                    Personal1Excel excel = new Personal1Excel();
                    BeanUtil.copyProperties(record, excel);
                    list.add(excel);
                }
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("个人接待汇总", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
            ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
            EasyExcel.write(response.getOutputStream(), Personal1Excel.class)
                    .sheet("个人接待汇总")
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .registerWriteHandler(widthStyleStrategy)
                    .doWrite(list);
        } else {
            throw new RRException("参数缺失");
        }
    }

    /**
     * personalShopPage
     *
     * @param response
     */
    @Override
    public void personal2(ExcelReq req, HttpServletResponse response) throws IOException {
        List<YkfCustomerSubAccountEntity> dataList = ykfCustomerSubAccountService.personalShopList();
        List<Personal2Excel> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dataList)) {
            for (YkfCustomerSubAccountEntity record : dataList) {
                Personal2Excel excel = new Personal2Excel();
                BeanUtil.copyProperties(record, excel);
                list.add(excel);
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("个人店铺", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), Personal2Excel.class)
                .sheet("个人店铺")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
                .doWrite(list);
    }

    /**
     * personalServiceDataPage
     *
     * @param req
     * @param response
     */
    @Override
    public void personal3(ExcelReq req, HttpServletResponse response) throws IOException {
        if (ObjectUtil.isNotEmpty(req)
                && ObjectUtil.isNotEmpty(req)
                && ObjectUtil.isNotEmpty(req.getDateStart())
                && ObjectUtil.isNotEmpty(req.getDateEnd())) {
            QueryWrapper<YkfAccountInputRecordEntity> queryWrapper = new QueryWrapper<>();
            if (ObjectUtil.isNotEmpty(req.getDateStart())) {
                queryWrapper.lambda().ge(YkfAccountInputRecordEntity::getDate, req.getDateStart());
            }
            if (ObjectUtil.isNotEmpty(req.getDateEnd())) {
                queryWrapper.lambda().le(YkfAccountInputRecordEntity::getDate, req.getDateEnd());
            }
            //过滤userId
            QueryWrapper<YkfCustomerSubAccountEntity> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(YkfCustomerSubAccountEntity::getUserId, CommonUtils.getUserId());
            List<YkfCustomerSubAccountEntity> accountList = subAccountService.list(queryWrapper1);
            List<Personal3Excel> list = new ArrayList<>();
            if (ObjectUtil.isNotEmpty(accountList)) {
                List<Long> subAccountIds = accountList.stream().map(YkfCustomerSubAccountEntity::getSubAccountId).collect(Collectors.toList());
                queryWrapper.lambda().in(YkfAccountInputRecordEntity::getSubAccountId, subAccountIds);
                List<YkfAccountInputRecordEntity> dataList = this.list(queryWrapper);
                if (ObjectUtil.isNotEmpty(dataList)) {
                    for (YkfAccountInputRecordEntity record : dataList) {
                        Personal3Excel excel = new Personal3Excel();
                        BeanUtil.copyProperties(record, excel);
                        list.add(excel);
                    }
                }
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("个人服务数据", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
            ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
            EasyExcel.write(response.getOutputStream(), Personal3Excel.class)
                    .sheet("个人服务数据")
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .registerWriteHandler(widthStyleStrategy)
                    .doWrite(list);
        } else {
            throw new RRException("参数缺失");
        }
    }

    /**
     * personalCommissionCheckPage
     *
     * @param req
     * @param response
     */
    @Override
    public void personal4(ExcelReq req, HttpServletResponse response) throws IOException {
        if (ObjectUtil.isNotEmpty(req)
                && ObjectUtil.isNotEmpty(req.getMonth())) {
            List<CommissionModel> dataList = personalCommissionCheckList(req);
            List<Personal4Excel> list = new ArrayList<>();
            if (ObjectUtil.isNotEmpty(dataList)) {
                for (CommissionModel record : dataList) {
                    Personal4Excel excel = new Personal4Excel();
                    BeanUtil.copyProperties(record, excel);
                    list.add(excel);
                }
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("个人提成核对", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
            ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
            EasyExcel.write(response.getOutputStream(), Personal4Excel.class)
                    .sheet("个人提成核对")
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .registerWriteHandler(widthStyleStrategy)
                    .doWrite(list);
        } else {
            throw new RRException("参数缺失");
        }
    }

    @Override
    public void commissionVerification(ExcelReq req, HttpServletResponse response) throws IOException {
//        if (ObjectUtil.isNotEmpty(req)
//                && ObjectUtil.isNotEmpty(req.getMonth())) {
//
//        } else {
//            throw new RRException("参数缺失");
//        }
//        YkfAccountInputRecordEntity accountInputRecord = new YkfAccountInputRecordEntity();
//        accountInputRecord.setMonth(req.getMonth());
        Map<String, Object> dataMap = commissionCheckPage3(req.getCondition(new TypeReference<YkfAccountInputRecordEntity>() {
        }));
        List<CommissionModel> dataList = (List<CommissionModel>) dataMap.get("list");
        List<CommissionVerificationExcel> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dataList)) {
            for (CommissionModel record : dataList) {
                CommissionVerificationExcel excel = new CommissionVerificationExcel();
                BeanUtil.copyProperties(record, excel);
                list.add(excel);
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("客服提成核对", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), CommissionVerificationExcel.class)
                .sheet("客服提成核对")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
                .doWrite(list);
    }

    @Override
    public void monthlyCommission(ExcelReq req, HttpServletResponse response) throws IOException {
//        if (ObjectUtil.isNotEmpty(req)
//                && ObjectUtil.isNotEmpty(req.getMonth())) {
//        } else {
//            throw new RRException("参数缺失");
//        }
//        YkfAccountInputRecordEntity accountInputRecord = new YkfAccountInputRecordEntity();
//        accountInputRecord.setMonth(req.getMonth());
        List<CommissionModel> dataList = sumCommissionCheckPage(req.getCondition(new TypeReference<YkfAccountInputRecordEntity>() {
        }));
        List<MonthlyCommissionExcel> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dataList)) {
            for (CommissionModel record : dataList) {
                MonthlyCommissionExcel excel = new MonthlyCommissionExcel();
                BeanUtil.copyProperties(record, excel);
                if (null == record.getBecomeRegularStatus()) {
                    record.setBecomeRegularStatus(1);
                }
                if (null == record.getOnDutyStatus()) {
                    record.setOnDutyStatus(1);
                }
                excel.setBecomeRegularStatus(record.getBecomeRegularStatus() == 0 ? "试用期" : "已转正");
                excel.setOnDutyStatus(record.getOnDutyStatus() == 0 ? "离职" : "在职");
                list.add(excel);
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("客服月提成汇总", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), MonthlyCommissionExcel.class)
                .sheet("个人提成核对")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
                .doWrite(list);
    }

    @Override
    public List<Map<String, Object>> toBeEnteredList() {
        List<Map<String, Object>> rspList = new ArrayList<>();
        YkfAccountInputRecordEntity condition = new YkfAccountInputRecordEntity();
        //查询所有满足条件的子账号
        List<ToBeEnteredRsp> subAccountList2 = baseMapper.getSubAccountList2(condition);
        if (ObjectUtil.isNotEmpty(subAccountList2)) {
            List<ToBeEnteredRsp> newList = new ArrayList<>();
            for (ToBeEnteredRsp toBeEnteredRsp : subAccountList2) {
                DateTime dateTime = DateUtil.parseDate(toBeEnteredRsp.getDate());
                newList.add(toBeEnteredRsp);
                for (int i = 0; i < 6; i++) {
                    DateTime date = DateUtil.offsetDay(dateTime, (i + 1) * (-1));
                    ToBeEnteredRsp newRsp = new ToBeEnteredRsp();
                    BeanUtil.copyProperties(toBeEnteredRsp, newRsp);
                    newRsp.setDate(DateUtil.formatDate(date));
                    newList.add(newRsp);
                }
            }
            Map<String, List<ToBeEnteredRsp>> collect = newList.stream().collect(Collectors.groupingBy(ToBeEnteredRsp::getShopName));
            for (String key : collect.keySet()) {
                Map<String, Object> map = new HashMap<>();
                map.put("shopName", key);
                map.put("list", collect.get(key));
                rspList.add(map);
            }
        }
        return rspList;
    }

    /**
     * 导出服务费统计
     *
     * @param req
     * @param response
     */
    @Override
    public void serviceCharge(ExcelReq req, HttpServletResponse response) throws IOException {
        List<ServiceChargeExcel> list = serviceExcelData(req);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("服务费统计表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), ServiceChargeExcel.class)
                .sheet("服务费统计表")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
                .doWrite(list);
    }

    private Map<String, BigDecimal> countCommission(YkfAccountInputRecordEntity record, List<String> dateList, Map<String, List<YkfSubAccountRecordEntity>> collect1, long days) {
        Map<String, BigDecimal> resultMap = new HashMap<>();
        String date = DateUtil.formatDate(record.getDate());
        String matchDate = "";
        //日期匹配，前闭后开
        for (int i = 0; i < dateList.size(); i++) {
            String itemDate = dateList.get(i);
            if (i == dateList.size() - 1) {
                if (date.compareTo(itemDate) >= 0) {
                    matchDate = itemDate;
                }
            } else {
                String nextItemDate = dateList.get(i + 1);
                if (date.compareTo(itemDate) >= 0 && date.compareTo(nextItemDate) < 0) {
                    matchDate = itemDate;
                    break;
                }
            }
        }
        if (StrUtil.isNotBlank(matchDate)) {
            List<YkfSubAccountRecordEntity> ykfSubAccountRecordEntities = collect1.get(matchDate);
            ykfSubAccountRecordEntities.sort(Comparator.comparing(YkfSubAccountRecordEntity::getCreateTime));
            YkfSubAccountRecordEntity subAccountRecord = ykfSubAccountRecordEntities.get(ykfSubAccountRecordEntities.size() - 1);
            //约定底薪
            BigDecimal monthConventionSalary = subAccountRecord.getConventionSalary();
            //计算底薪收益
            BigDecimal conventionSalary = monthConventionSalary.divide(new BigDecimal(days), 2, RoundingMode.HALF_UP);
            //提成比例
            BigDecimal commissionRatio = ObjectUtil.isEmpty(subAccountRecord.getCommissionRatio()) ? BigDecimal.ZERO : subAccountRecord.getCommissionRatio();
            //销售额
            BigDecimal salesRevenue = record.getSalesRevenue();
            //提成效益=销售额*提成比例
            BigDecimal commissionSalary = salesRevenue.multiply(commissionRatio).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);

            resultMap.put("conventionSalary", conventionSalary);
            resultMap.put("commissionSalary", commissionSalary);
        } else {
            resultMap.put("conventionSalary", BigDecimal.ZERO);
            resultMap.put("commissionSalary", BigDecimal.ZERO);
        }
        return resultMap;
    }

    @Override
    public PageUtils sumSalesRevenuePage(ParamsModel<YkfAccountInputRecordEntity> params) {
        if (ObjectUtil.isNotEmpty(params)
                && ObjectUtil.isNotEmpty(params.getCondition())
                && ObjectUtil.isNotEmpty(params.getCondition().getMonthStart())
                && ObjectUtil.isNotEmpty(params.getCondition().getMonthEnd())) {
            IPage<YkfAccountInputRecordEntity> page = new Query<YkfAccountInputRecordEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
//            List<Long> powerUserIds = sysUserService.getPowerUserIds();
//            params.getCondition().setCreateUserIds(powerUserIds);
            List<Long> powerSubAccountIds = sysUserService.getPowerSubAccountIds();
            if (ObjectUtil.isEmpty(powerSubAccountIds)) {
                return new PageUtils();
            } else {
                if (!powerSubAccountIds.contains(0L)) {
                    params.getCondition().setPowerSubAccountIds(powerSubAccountIds);
                }
            }
            IPage<YkfAccountInputRecordEntity> resultPage = baseMapper.sumSalesRevenuePage(page, params.getCondition());
            BigDecimal sum = baseMapper.sumSalesRevenue(params.getCondition());
            Map<String, Object> map = new HashMap<>();
            map.put("sumSalary", sum);
            return new PageUtils(resultPage, map);
        } else {
            throw new RRException("参数缺失");
        }
    }


    @Override
    public PageUtils sumInputCountPage(ParamsModel<YkfAccountInputRecordEntity> params) {
        if (ObjectUtil.isNotEmpty(params)
                && ObjectUtil.isNotEmpty(params.getCondition())
                && ObjectUtil.isNotEmpty(params.getCondition().getDateStart())
                && ObjectUtil.isNotEmpty(params.getCondition().getDateEnd())) {
            IPage<YkfAccountInputRecordEntity> page = new Query<YkfAccountInputRecordEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
//            List<Long> powerUserIds = sysUserService.getPowerUserIds();
//            params.getCondition().setCreateUserIds(powerUserIds);
            List<Long> powerSubAccountIds = sysUserService.getPowerSubAccountIds();
            if (ObjectUtil.isEmpty(powerSubAccountIds)) {
                return new PageUtils();
            } else {
                if (!powerSubAccountIds.contains(0L)) {
                    params.getCondition().setPowerSubAccountIds(powerSubAccountIds);
                }
            }
            IPage<YkfAccountInputRecordEntity> resultPage = baseMapper.sumInputCountPage(page, params.getCondition());
            BigDecimal sum = baseMapper.sumInputCount(params.getCondition());
            Map<String, Object> map = new HashMap<>();
            map.put("sumCount", sum);
            return new PageUtils(resultPage, map);
        } else {
            throw new RRException("参数缺失");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void editRecord(YkfAccountInputRecordEntity params) {
        if (ObjectUtil.isNotEmpty(params) && ObjectUtil.isNotEmpty(params.getInputRecordIds())) {
            UpdateWrapper<YkfAccountInputRecordEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().in(YkfAccountInputRecordEntity::getInputRecordId, params.getInputRecordIds())
                    .set(YkfAccountInputRecordEntity::getQARatioIgnore, params.getQARatioIgnore())
                    .set(YkfAccountInputRecordEntity::getResponseRateIgnore, params.getResponseRateIgnore())
                    .set(YkfAccountInputRecordEntity::getResponseTimeIgnore, params.getResponseTimeIgnore())
                    .set(YkfAccountInputRecordEntity::getConversionRateIgnore, params.getConversionRateIgnore());
            this.update(updateWrapper);
        }
    }

    @Override
    public PageUtils sumCustomerPage(ParamsModel<YkfAccountInputRecordEntity> params) {
        if (ObjectUtil.isNotEmpty(params)
                && ObjectUtil.isNotEmpty(params.getCondition())
                && ObjectUtil.isNotEmpty(params.getCondition().getDateStart())
                && ObjectUtil.isNotEmpty(params.getCondition().getDateEnd())) {
            long days = DateUtil.betweenDay(params.getCondition().getDateStart(), params.getCondition().getDateEnd(), false) + 1;
            IPage<YkfAccountInputRecordEntity> page = new Query<YkfAccountInputRecordEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
            List<Long> powerSubAccountIds = sysUserService.getPowerSubAccountIds();
            if (ObjectUtil.isEmpty(powerSubAccountIds)) {
                return new PageUtils();
            } else {
                if (!powerSubAccountIds.contains(0L)) {
                    params.getCondition().setPowerSubAccountIds(powerSubAccountIds);
                }
            }
            int lvl = 1;
            IPage<YkfAccountInputRecordEntity> resultPage = null;
            if (ObjectUtil.isNotEmpty(params.getCondition().getUserId()) && ObjectUtil.isNotEmpty(params.getCondition().getDate())) {
                resultPage = baseMapper.sumCustomerPage3(page, params.getCondition());
                lvl = 3;
            } else if (ObjectUtil.isNotEmpty(params.getCondition().getUserId())) {
                resultPage = baseMapper.sumCustomerPage2(page, params.getCondition());
                lvl = 2;
            } else {
                resultPage = baseMapper.sumCustomerPage(page, params.getCondition());
            }
            BigDecimal sumRestDays = BigDecimal.ZERO;
            if (ObjectUtil.isNotEmpty(resultPage) && ObjectUtil.isNotEmpty(resultPage.getRecords())) {
                for (YkfAccountInputRecordEntity record : resultPage.getRecords()) {
                    String inputRecordIdStr = record.getInputRecordIdStr();
                    List<String> inputRecordIds = new ArrayList<>();
                    if (StrUtil.isNotBlank(inputRecordIdStr)) {
                        inputRecordIds = StrUtil.split(inputRecordIdStr, ',');
                    }
                    record.setDateStart(params.getCondition().getDateStart());
                    record.setDateEnd(params.getCondition().getDateEnd());
                    BigDecimal averageReceptionVolume = record.getAverageReceptionVolume();
                    if (ObjectUtil.isNotEmpty(averageReceptionVolume)) {
                        BigDecimal decimal = averageReceptionVolume.divide(new BigDecimal(days), 0, RoundingMode.HALF_UP);
                        record.setAverageDayReceptionVolume(decimal);
                    } else {
                        record.setAverageDayReceptionVolume(BigDecimal.ZERO);
                    }
                    if (lvl == 3) {
                        Long userId = record.getUserId();
                        Date date = record.getDate();
                        Long subAccountId = record.getSubAccountId();
                        List<YkfAccountInputRecordEntity> list1 = baseMapper.customerNotIgnoreLvl3(inputRecordIds, userId, date, subAccountId, 0);
                        if (ObjectUtil.isNotEmpty(list1)) {
                            YkfAccountInputRecordEntity item = list1.get(0);
                            record.setSumIgnoreReceptionVolume(item.getSumIgnoreReceptionVolume());
                            BigDecimal decimal = item.getSumIgnoreReceptionVolume().divide(new BigDecimal(item.getSumCount()), 0, RoundingMode.HALF_UP).divide(new BigDecimal(days), 0, RoundingMode.HALF_UP);
                            record.setAverageIgnoreDayReceptionVolume(decimal);
                        } else {
                            record.setSumIgnoreReceptionVolume(BigDecimal.ZERO);
                            record.setAverageIgnoreDayReceptionVolume(BigDecimal.ZERO);
                        }
                        List<YkfAccountInputRecordEntity> list2 = baseMapper.customerNotIgnoreLvl3(inputRecordIds, userId, date, subAccountId, 2);
                        if (ObjectUtil.isNotEmpty(list2)) {
                            YkfAccountInputRecordEntity item = list2.get(0);
                            record.setAverageIgnoreResponseTime(item.getAverageIgnoreResponseTime());
                        }
                        List<YkfAccountInputRecordEntity> list3 = baseMapper.customerNotIgnoreLvl3(inputRecordIds, userId, date, subAccountId, 3);
                        if (ObjectUtil.isNotEmpty(list3)) {
                            YkfAccountInputRecordEntity item = list3.get(0);
                            record.setAverageIgnoreQARatio(item.getAverageIgnoreQARatio());
                        }
                        List<YkfAccountInputRecordEntity> list4 = baseMapper.customerNotIgnoreLvl3(inputRecordIds, userId, date, subAccountId, 4);
                        if (ObjectUtil.isNotEmpty(list4)) {
                            YkfAccountInputRecordEntity item = list4.get(0);
                            record.setAverageIgnoreResponseRate(item.getAverageIgnoreResponseRate());
                        }
                        QueryWrapper<YkfAccountInputRecordEntity> queryWrapper = new QueryWrapper<>();
                        queryWrapper.lambda().eq(YkfAccountInputRecordEntity::getDate, date)
                                .eq(YkfAccountInputRecordEntity::getSubAccountId, subAccountId)
                                .and(wrapper -> wrapper.eq(YkfAccountInputRecordEntity::getConversionRateIgnore, 1)
                                        .or().eq(YkfAccountInputRecordEntity::getResponseTimeIgnore, 1)
                                        .or().eq(YkfAccountInputRecordEntity::getResponseRateIgnore, 1)
                                        .or().eq(YkfAccountInputRecordEntity::getQARatioIgnore, 1));
                        int count = this.count(queryWrapper);
                        record.setIgnoreCount(count);
//                        record.setIgnoreProportion((record.getIgnoreCount() / record.getSumCount()) * 100 + "%");
                        record.setIgnoreProportion(new BigDecimal(count).multiply(new BigDecimal(100)).divide(new BigDecimal(record.getSumCount()), 2, RoundingMode.HALF_UP).toString() + "%");

                        //查询用户请假天数
                        QueryWrapper<YkfUserAttendanceRecordEntity> queryWrapper1 = new QueryWrapper<>();
                        queryWrapper1.lambda()
//                                .eq(YkfUserAttendanceRecordEntity::getAttendanceDate, record.getDate())
                                .ge(YkfUserAttendanceRecordEntity::getAttendanceDate, params.getCondition().getDateStart())
                                .le(YkfUserAttendanceRecordEntity::getAttendanceDate, params.getCondition().getDateEnd())
                                .eq(YkfUserAttendanceRecordEntity::getUserId, record.getUserId())
                                .and(wrapper -> wrapper.eq(YkfUserAttendanceRecordEntity::getType, 1)
                                        .or().eq(YkfUserAttendanceRecordEntity::getType, 3));
                        int count1 = attendanceRecordService.count(queryWrapper1);
                        BigDecimal restDays = BigDecimal.valueOf(count1);
                        record.setRestDays(restDays);
                        sumRestDays = sumRestDays.add(restDays);
                        record.setRestDays(restDays);
                    } else if (lvl == 2) {
                        Long userId = record.getUserId();
                        List<Long> subAccountIds = getSubAccountIdsByUserId(userId);
                        Date date = record.getDate();
                        List<YkfAccountInputRecordEntity> list1 = baseMapper.customerNotIgnoreLvl2(inputRecordIds, userId, date, 0);
                        if (ObjectUtil.isNotEmpty(list1)) {
                            YkfAccountInputRecordEntity item = list1.get(0);
                            record.setSumIgnoreReceptionVolume(item.getSumIgnoreReceptionVolume());
                            BigDecimal decimal = item.getSumIgnoreReceptionVolume().divide(new BigDecimal(item.getSumCount()), 0, RoundingMode.HALF_UP).divide(new BigDecimal(days), 0, RoundingMode.HALF_UP);
                            record.setAverageIgnoreDayReceptionVolume(decimal);
                        } else {
                            record.setSumIgnoreReceptionVolume(BigDecimal.ZERO);
                            record.setAverageIgnoreDayReceptionVolume(BigDecimal.ZERO);
                        }
                        List<YkfAccountInputRecordEntity> list2 = baseMapper.customerNotIgnoreLvl2(inputRecordIds, userId, date, 2);
                        if (ObjectUtil.isNotEmpty(list2)) {
                            YkfAccountInputRecordEntity item = list2.get(0);
                            record.setAverageIgnoreResponseTime(item.getAverageIgnoreResponseTime());
                        }
                        List<YkfAccountInputRecordEntity> list3 = baseMapper.customerNotIgnoreLvl2(inputRecordIds, userId, date, 3);
                        if (ObjectUtil.isNotEmpty(list3)) {
                            YkfAccountInputRecordEntity item = list3.get(0);
                            record.setAverageIgnoreQARatio(item.getAverageIgnoreQARatio());
                        }
                        List<YkfAccountInputRecordEntity> list4 = baseMapper.customerNotIgnoreLvl2(inputRecordIds, userId, date, 4);
                        if (ObjectUtil.isNotEmpty(list4)) {
                            YkfAccountInputRecordEntity item = list4.get(0);
                            record.setAverageIgnoreResponseRate(item.getAverageIgnoreResponseRate());
                        }
                        QueryWrapper<YkfAccountInputRecordEntity> queryWrapper = new QueryWrapper<>();
                        queryWrapper.lambda().in(YkfAccountInputRecordEntity::getSubAccountId, subAccountIds)
                                .eq(YkfAccountInputRecordEntity::getDate, date);
                        queryWrapper.lambda().and(wrapper -> wrapper.eq(YkfAccountInputRecordEntity::getConversionRateIgnore, 1)
                                .or().eq(YkfAccountInputRecordEntity::getResponseTimeIgnore, 1)
                                .or().eq(YkfAccountInputRecordEntity::getResponseRateIgnore, 1)
                                .or().eq(YkfAccountInputRecordEntity::getQARatioIgnore, 1));
                        int count = this.count(queryWrapper);
                        record.setIgnoreCount(count);
//                        record.setIgnoreProportion((record.getIgnoreCount() / record.getSumCount()) * 100 + "%");
                        record.setIgnoreProportion(new BigDecimal(count).multiply(new BigDecimal(100)).divide(new BigDecimal(record.getSumCount()), 2, RoundingMode.HALF_UP).toString() + "%");
                        //查询用户请假天数
                        QueryWrapper<YkfUserAttendanceRecordEntity> queryWrapper1 = new QueryWrapper<>();
                        queryWrapper1.lambda()
                                .eq(YkfUserAttendanceRecordEntity::getAttendanceDate, record.getDate())
                                .eq(YkfUserAttendanceRecordEntity::getUserId, record.getUserId())
                                .and(wrapper -> wrapper.eq(YkfUserAttendanceRecordEntity::getType, 1)
                                        .or().eq(YkfUserAttendanceRecordEntity::getType, 3));
                        int count1 = attendanceRecordService.count(queryWrapper1);
                        BigDecimal restDays = BigDecimal.valueOf(count1);
                        record.setRestDays(restDays);
                        sumRestDays = sumRestDays.add(restDays);
                        record.setRestDays(restDays);
                    } else {
                        Long userId = record.getUserId();
                        List<Long> subAccountIdsByUserId = getSubAccountIdsByUserId(userId);
                        List<YkfAccountInputRecordEntity> list1 = baseMapper.customerNotIgnoreLvl1(inputRecordIds, userId, 0);
                        if (ObjectUtil.isNotEmpty(list1)) {
                            YkfAccountInputRecordEntity item = list1.get(0);
                            record.setSumIgnoreReceptionVolume(item.getSumIgnoreReceptionVolume());
                            BigDecimal decimal = item.getSumIgnoreReceptionVolume().divide(new BigDecimal(item.getSumCount()), 0, RoundingMode.HALF_UP).divide(new BigDecimal(days), 0, RoundingMode.HALF_UP);
                            record.setAverageIgnoreDayReceptionVolume(decimal);
                        } else {
                            record.setSumIgnoreReceptionVolume(BigDecimal.ZERO);
                            record.setAverageIgnoreDayReceptionVolume(BigDecimal.ZERO);
                        }
                        List<YkfAccountInputRecordEntity> list2 = baseMapper.customerNotIgnoreLvl1(inputRecordIds, userId, 2);
                        if (ObjectUtil.isNotEmpty(list2)) {
                            YkfAccountInputRecordEntity item = list2.get(0);
                            record.setAverageIgnoreResponseTime(item.getAverageIgnoreResponseTime());
                        }
                        List<YkfAccountInputRecordEntity> list3 = baseMapper.customerNotIgnoreLvl1(inputRecordIds, userId, 3);
                        if (ObjectUtil.isNotEmpty(list3)) {
                            YkfAccountInputRecordEntity item = list3.get(0);
                            record.setAverageIgnoreQARatio(item.getAverageIgnoreQARatio());
                        }
                        List<YkfAccountInputRecordEntity> list4 = baseMapper.customerNotIgnoreLvl1(inputRecordIds, userId, 4);
                        if (ObjectUtil.isNotEmpty(list4)) {
                            YkfAccountInputRecordEntity item = list4.get(0);
                            record.setAverageIgnoreResponseRate(item.getAverageIgnoreResponseRate());
                        }
                        QueryWrapper<YkfAccountInputRecordEntity> queryWrapper = new QueryWrapper<>();
                        queryWrapper.lambda().in(YkfAccountInputRecordEntity::getSubAccountId, subAccountIdsByUserId)
                                .and(wrapper -> wrapper.eq(YkfAccountInputRecordEntity::getConversionRateIgnore, 1)
                                        .or().eq(YkfAccountInputRecordEntity::getResponseTimeIgnore, 1)
                                        .or().eq(YkfAccountInputRecordEntity::getResponseRateIgnore, 1)
                                        .or().eq(YkfAccountInputRecordEntity::getQARatioIgnore, 1));
                        int count = this.count(queryWrapper);
                        record.setIgnoreCount(count);
//                        record.setIgnoreProportion((record.getIgnoreCount() / record.getSumCount()) * 100 + "%");
                        record.setIgnoreProportion(new BigDecimal(count).multiply(new BigDecimal(100)).divide(new BigDecimal(record.getSumCount()), 2, RoundingMode.HALF_UP).toString() + "%");
                        //查询用户请假天数
                        QueryWrapper<YkfUserAttendanceRecordEntity> queryWrapper1 = new QueryWrapper<>();
                        queryWrapper1.lambda()
                                .eq(YkfUserAttendanceRecordEntity::getAttendanceDate, record.getDate())
                                .eq(YkfUserAttendanceRecordEntity::getUserId, record.getUserId())
                                .and(wrapper -> wrapper.eq(YkfUserAttendanceRecordEntity::getType, 1)
                                        .or().eq(YkfUserAttendanceRecordEntity::getType, 3));
                        int count1 = attendanceRecordService.count(queryWrapper1);
                        BigDecimal restDays = BigDecimal.valueOf(count1);
                        record.setRestDays(restDays);
                        sumRestDays = sumRestDays.add(restDays);
                        record.setRestDays(restDays);
                    }
                }
            }
            List<YkfAccountInputSumModel> ykfAccountInputSumModels = baseMapper.sumCustomer(params.getCondition());
            Map<String, Object> extentParams = new HashMap<>();
            if (ObjectUtil.isNotEmpty(ykfAccountInputSumModels)) {
                YkfAccountInputSumModel ykfAccountInputSumModel = ykfAccountInputSumModels.get(0);
                if (ykfAccountInputSumModel.getSumCount() > 0) {
                    BigDecimal sumReceptionVolume = ykfAccountInputSumModel.getSumReceptionVolume();
                    if (ObjectUtil.isNotEmpty(sumReceptionVolume)) {
                        BigDecimal decimal = sumReceptionVolume.divide(new BigDecimal(ykfAccountInputSumModel.getSumCount()), 0, RoundingMode.HALF_UP).divide(new BigDecimal(days), 0, RoundingMode.HALF_UP);
                        ykfAccountInputSumModel.setAverageDayReceptionVolume(decimal);
                    } else {
                        ykfAccountInputSumModel.setAverageDayReceptionVolume(BigDecimal.ZERO);
                    }
                    List<YkfAccountInputSumModel> ykfAccountInputSumModels1 = baseMapper.sumCustomerNotIgnore(params.getCondition(), 0);
                    if (ObjectUtil.isNotEmpty(ykfAccountInputSumModels1)) {
                        YkfAccountInputSumModel item = ykfAccountInputSumModels1.get(0);
                        ykfAccountInputSumModel.setSumIgnoreReceptionVolume(item.getSumIgnoreReceptionVolume());
                        BigDecimal decimal = item.getSumIgnoreReceptionVolume().divide(new BigDecimal(item.getSumCount()), 0, RoundingMode.HALF_UP).divide(new BigDecimal(days), 0, RoundingMode.HALF_UP);
                        ykfAccountInputSumModel.setAverageIgnoreDayReceptionVolume(decimal);
                    } else {
                        ykfAccountInputSumModel.setSumIgnoreReceptionVolume(BigDecimal.ZERO);
                        ykfAccountInputSumModel.setAverageIgnoreDayReceptionVolume(BigDecimal.ZERO);
                    }
                    List<YkfAccountInputSumModel> ykfAccountInputSumModels2 = baseMapper.sumCustomerNotIgnore(params.getCondition(), 2);
                    if (ObjectUtil.isNotEmpty(ykfAccountInputSumModels2)) {
                        YkfAccountInputSumModel item = ykfAccountInputSumModels2.get(0);
                        ykfAccountInputSumModel.setAverageIgnoreResponseTime(item.getAverageIgnoreResponseTime());
                    }
                    List<YkfAccountInputSumModel> ykfAccountInputSumModels3 = baseMapper.sumCustomerNotIgnore(params.getCondition(), 3);
                    if (ObjectUtil.isNotEmpty(ykfAccountInputSumModels3)) {
                        YkfAccountInputSumModel item = ykfAccountInputSumModels3.get(0);
                        ykfAccountInputSumModel.setAverageIgnoreQARatio(item.getAverageIgnoreQARatio());
                    }
                    List<YkfAccountInputSumModel> ykfAccountInputSumModels4 = baseMapper.sumCustomerNotIgnore(params.getCondition(), 4);
                    if (ObjectUtil.isNotEmpty(ykfAccountInputSumModels4)) {
                        YkfAccountInputSumModel item = ykfAccountInputSumModels4.get(0);
                        ykfAccountInputSumModel.setAverageIgnoreResponseRate(item.getAverageIgnoreResponseRate());
                    }
                    QueryWrapper<YkfAccountInputRecordEntity> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().and(wrapper -> wrapper.eq(YkfAccountInputRecordEntity::getConversionRateIgnore, 1)
                            .or().eq(YkfAccountInputRecordEntity::getResponseTimeIgnore, 1)
                            .or().eq(YkfAccountInputRecordEntity::getResponseRateIgnore, 1)
                            .or().eq(YkfAccountInputRecordEntity::getQARatioIgnore, 1));
                    int count = this.count(queryWrapper);
                    ykfAccountInputSumModel.setIgnoreCount(count);
                    if (ykfAccountInputSumModel.getSumCount() > 0) {
//                        ykfAccountInputSumModel.setIgnoreProportion((ykfAccountInputSumModel.getIgnoreCount() / ykfAccountInputSumModel.getSumCount()) * 100 + "%");
                        ykfAccountInputSumModel.setIgnoreProportion(new BigDecimal(count).multiply(new BigDecimal(100)).divide(new BigDecimal(ykfAccountInputSumModel.getSumCount()), 2, RoundingMode.HALF_UP).toString() + "%");

                    } else {
                        ykfAccountInputSumModel.setIgnoreProportion("0%");
                    }
                    ykfAccountInputSumModel.setRestDays(sumRestDays);
                    extentParams = BeanUtil.beanToMap(ykfAccountInputSumModel);
                }
            }
            return new PageUtils(resultPage, extentParams);
        } else {
            throw new RRException("参数缺失");
        }
    }

    private List<Long> getSubAccountIdsByUserId(Long userId) {
        QueryWrapper<YkfCustomerSubAccountEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(YkfCustomerSubAccountEntity::getUserId, userId);
        List<YkfCustomerSubAccountEntity> list = subAccountService.list(queryWrapper);
        if (ObjectUtil.isNotEmpty(list)) {
            return list.stream().map(YkfCustomerSubAccountEntity::getSubAccountId).distinct().collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public PageUtils queryPage(ParamsModel<YkfAccountInputRecordEntity> params) {
        if (ObjectUtil.isEmpty(params.getSort()) || StrUtil.isBlank(params.getSort().getSidx()) || StrUtil.isBlank(params.getSort().getOrder())) {
            ParamsModel.SortParams sortParams = new ParamsModel.SortParams();
            sortParams.setSidx("date");
            sortParams.setOrder("desc");
            params.setSort(sortParams);
        }
        QueryWrapper<YkfAccountInputRecordEntity> queryWrapper = ParamUtils.createQueryWrapperByDefaultSort(params);
        YkfAccountInputRecordEntity condition = params.getCondition();
        if (StrUtil.isNotBlank(condition.getKeyword())) {
            queryWrapper.lambda().and(wrapper -> wrapper.like(YkfAccountInputRecordEntity::getAccountNo, condition.getKeyword())
                    .or().like(YkfAccountInputRecordEntity::getAccountName, condition.getKeyword())
                    .or().like(YkfAccountInputRecordEntity::getShopName, condition.getKeyword()));
        }
        boolean selectFlag = false;
        QueryWrapper<YkfCustomerSubAccountEntity> queryWrapper1 = new QueryWrapper<>();
        //筛选子账号
        if (StrUtil.isNotBlank(condition.getCustomerName())) {
            selectFlag = true;
            queryWrapper1.lambda().like(YkfCustomerSubAccountEntity::getCustomerName, condition.getCustomerName());
        }
        if (StrUtil.isNotBlank(condition.getName())) {
            selectFlag = true;
            queryWrapper1.lambda().like(YkfCustomerSubAccountEntity::getName, condition.getName());
        }
        if (StrUtil.isNotBlank(condition.getFlowerName())) {
            selectFlag = true;
            queryWrapper1.lambda().like(YkfCustomerSubAccountEntity::getFlowerName, condition.getFlowerName());
        }
        if (selectFlag) {
            List<YkfCustomerSubAccountEntity> list = subAccountService.list(queryWrapper1);
            if (ObjectUtil.isEmpty(list)) {
                IPage<YkfAccountInputRecordEntity> page = new Query<YkfAccountInputRecordEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
                return new PageUtils(page, new HashMap<>());
            } else {
                List<Long> subAccountIds = list.stream().map(YkfCustomerSubAccountEntity::getSubAccountId).distinct().collect(Collectors.toList());
                queryWrapper.lambda().in(YkfAccountInputRecordEntity::getSubAccountId, subAccountIds);
            }
        }
        if (ObjectUtil.isNotEmpty(condition.getDateStart())) {
            queryWrapper.lambda().ge(YkfAccountInputRecordEntity::getDate, condition.getDateStart());
        }
        if (ObjectUtil.isNotEmpty(condition.getDateStart())) {
            queryWrapper.lambda().le(YkfAccountInputRecordEntity::getDate, condition.getDateEnd());
        }
        if (ObjectUtil.isNotEmpty(condition.getCreateDateStart())) {
            DateTime dateTime = DateUtil.parseDateTime(DateUtil.formatDate(condition.getCreateDateStart()) + " 00:00:00");
            queryWrapper.lambda().ge(YkfAccountInputRecordEntity::getCreateTime, dateTime);
        }
        if (ObjectUtil.isNotEmpty(condition.getCreateDateEnd())) {
            DateTime dateTime = DateUtil.parseDateTime(DateUtil.formatDate(condition.getCreateDateEnd()) + " 23:59:59");
            queryWrapper.lambda().le(YkfAccountInputRecordEntity::getCreateTime, dateTime);
        }
        if (ObjectUtil.isNotEmpty(condition.getSalesRevenueStart())) {
            queryWrapper.lambda().ge(YkfAccountInputRecordEntity::getSalesRevenue, condition.getSalesRevenueStart());
        }
        if (ObjectUtil.isNotEmpty(condition.getSalesRevenueEnd())) {
            queryWrapper.lambda().le(YkfAccountInputRecordEntity::getSalesRevenue, condition.getSalesRevenueEnd());
        }
        if (ObjectUtil.isNotEmpty(condition.getReceptionVolumeStart())) {
            queryWrapper.lambda().ge(YkfAccountInputRecordEntity::getReceptionVolume, condition.getReceptionVolumeStart());
        }
        if (ObjectUtil.isNotEmpty(condition.getReceptionVolumeEnd())) {
            queryWrapper.lambda().le(YkfAccountInputRecordEntity::getReceptionVolume, condition.getReceptionVolumeEnd());
        }
        if (ObjectUtil.isNotEmpty(condition.getConversionRateStart())) {
            queryWrapper.lambda().ge(YkfAccountInputRecordEntity::getConversionRate, condition.getConversionRateStart());
        }
        if (ObjectUtil.isNotEmpty(condition.getConversionRateEnd())) {
            queryWrapper.lambda().le(YkfAccountInputRecordEntity::getConversionRate, condition.getConversionRateEnd());
        }
        if (ObjectUtil.isNotEmpty(condition.getResponseTimeStart())) {
            queryWrapper.lambda().ge(YkfAccountInputRecordEntity::getResponseTime, condition.getResponseTimeStart());
        }
        if (ObjectUtil.isNotEmpty(condition.getResponseTimeEnd())) {
            queryWrapper.lambda().le(YkfAccountInputRecordEntity::getResponseTime, condition.getResponseTimeEnd());
        }
        if (ObjectUtil.isNotEmpty(condition.getQARatioStart())) {
            queryWrapper.lambda().ge(YkfAccountInputRecordEntity::getQARatio, condition.getQARatioStart());
        }
        if (ObjectUtil.isNotEmpty(condition.getQARatioEnd())) {
            queryWrapper.lambda().le(YkfAccountInputRecordEntity::getQARatio, condition.getQARatioEnd());
        }
        if (ObjectUtil.isNotEmpty(condition.getResponseRateStart())) {
            queryWrapper.lambda().ge(YkfAccountInputRecordEntity::getResponseRate, condition.getResponseRateStart());
        }
        if (ObjectUtil.isNotEmpty(condition.getResponseRateEnd())) {
            queryWrapper.lambda().le(YkfAccountInputRecordEntity::getResponseRate, condition.getResponseRateEnd());
        }
//        List<Long> powerUserIds = sysUserService.getPowerUserIds();
//        if (ObjectUtil.isNotEmpty(powerUserIds)) {
//            queryWrapper.lambda().in(YkfAccountInputRecordEntity::getCreateUserId, powerUserIds);
//        }
        List<Long> powerSubAccountIds = sysUserService.getPowerSubAccountIds();
        if (ObjectUtil.isEmpty(powerSubAccountIds)) {
            return new PageUtils();
        } else {
            if (!powerSubAccountIds.contains(0L)) {
                queryWrapper.lambda().in(YkfAccountInputRecordEntity::getSubAccountId, powerSubAccountIds);
            }
        }
        IPage<YkfAccountInputRecordEntity> page = this.page(
                new Query<YkfAccountInputRecordEntity>().getPage(BeanUtil.beanToMap(params.getPage())),
                queryWrapper
        );
        List<YkfAccountInputRecordEntity> list = this.list(queryWrapper);
        Map<String, Object> map = new HashMap<>();
        if (ObjectUtil.isNotEmpty(page) && ObjectUtil.isNotEmpty(page.getRecords())) {
            BigDecimal sumSalesRevenue = BigDecimal.ZERO;
            BigDecimal sumReceptionVolume = BigDecimal.ZERO;
            BigDecimal sumConversionRate = BigDecimal.ZERO;
            BigDecimal sumResponseTime = BigDecimal.ZERO;
            BigDecimal sumQARatio = BigDecimal.ZERO;
            BigDecimal sumResponseRate = BigDecimal.ZERO;
            for (YkfAccountInputRecordEntity record : page.getRecords()) {
                sumSalesRevenue = sumSalesRevenue.add(record.getSalesRevenue());
                sumReceptionVolume = sumReceptionVolume.add(record.getReceptionVolume());
                sumConversionRate = sumConversionRate.add(record.getConversionRate());
                sumResponseTime = sumResponseTime.add(record.getResponseTime());
                sumQARatio = sumQARatio.add(record.getQARatio());
                sumResponseRate = sumResponseRate.add(record.getResponseRate());
                //查询客服信息
                YkfCustomerSubAccountEntity byId = subAccountService.getById(record.getSubAccountId());
                if (ObjectUtil.isNotEmpty(byId)) {
                    SysUserEntity user = sysUserService.getById(byId.getUserId());
                    if (ObjectUtil.isNotEmpty(user)) {
                        record.setName(user.getName());
                        record.setFlowerName(user.getFlowerName());
                        record.setNo(user.getNo());
                    }
                    record.setCustomerName(byId.getCustomerName());
                }
                //查询店铺
                YkfCustomerShopEntity shop = customerShopService.getById(record.getShopId());
                if (ObjectUtil.isNotEmpty(shop)) {
                    record.setPlatformNo(shop.getPlatformNo());
                    record.setPlatformName(shop.getPlatformName());
                }
            }
            Map<String, Object> map1 = new HashMap<>();
            map1.put("salesRevenue", sumSalesRevenue);
            BigDecimal divide = new BigDecimal(page.getRecords().size());
            map1.put("receptionVolume", sumReceptionVolume);
            map1.put("conversionRate", sumConversionRate.divide(divide, 2, RoundingMode.HALF_UP));
            map1.put("responseTime", sumResponseTime.divide(divide, 2, RoundingMode.HALF_UP));
            map1.put("qARatio", sumQARatio.divide(divide, 2, RoundingMode.HALF_UP));
            map1.put("responseRate", sumResponseRate.divide(divide, 2, RoundingMode.HALF_UP));
            map.put("currentPage", map1);
        } else {
            map.put("currentPage", new HashMap<>());
        }
        if (ObjectUtil.isNotEmpty(list)) {
            BigDecimal sumSalesRevenue = BigDecimal.ZERO;
            BigDecimal sumReceptionVolume = BigDecimal.ZERO;
            BigDecimal sumConversionRate = BigDecimal.ZERO;
            BigDecimal sumResponseTime = BigDecimal.ZERO;
            BigDecimal sumQARatio = BigDecimal.ZERO;
            BigDecimal sumResponseRate = BigDecimal.ZERO;
            for (YkfAccountInputRecordEntity record : list) {
                sumSalesRevenue = sumSalesRevenue.add(record.getSalesRevenue());
                sumReceptionVolume = sumReceptionVolume.add(record.getReceptionVolume());
                sumConversionRate = sumConversionRate.add(record.getConversionRate());
                sumResponseTime = sumResponseTime.add(record.getResponseTime());
                sumQARatio = sumQARatio.add(record.getQARatio());
                sumResponseRate = sumResponseRate.add(record.getResponseRate());
            }
            Map<String, Object> map1 = new HashMap<>();
            map1.put("salesRevenue", sumSalesRevenue);
            BigDecimal divide = new BigDecimal(page.getRecords().size());
            map1.put("receptionVolume", sumReceptionVolume);
            map1.put("conversionRate", sumConversionRate.divide(divide, 2, RoundingMode.HALF_UP));
            map1.put("responseTime", sumResponseTime.divide(divide, 2, RoundingMode.HALF_UP));
            map1.put("qARatio", sumQARatio.divide(divide, 2, RoundingMode.HALF_UP));
            map1.put("responseRate", sumResponseRate.divide(divide, 2, RoundingMode.HALF_UP));
            map.put("allData", map1);
        } else {
            map.put("allData", new HashMap<>());
        }
        return new PageUtils(page, map);
    }

    @Override
    public PageUtils toBeEnteredPage(ParamsModel<YkfAccountInputRecordEntity> params) {
        if (ObjectUtil.isEmpty(params) || ObjectUtil.isEmpty(params.getCondition()) || ObjectUtil.isEmpty(params.getCondition().getDateStart())
                || ObjectUtil.isEmpty(params.getCondition().getDateEnd())) {
            throw new RRException("参数缺失");
        }
        YkfAccountInputRecordEntity condition = params.getCondition();
//        List<Long> powerUserIds = sysUserService.getPowerUserIds();
//        condition.setCreateUserIds(powerUserIds);
        List<Long> powerSubAccountIds = sysUserService.getPowerSubAccountIds();
        if (ObjectUtil.isEmpty(powerSubAccountIds)) {
            return new PageUtils();
        } else {
            if (!powerSubAccountIds.contains(0L)) {
                condition.setPowerSubAccountIds(powerSubAccountIds);
            }
        }
        //查询所有满足条件的子账号
        List<YkfAccountInputRecordEntity> subAccountList = baseMapper.getSubAccountList(condition);
        List<YkfAccountInputRecordEntity> resultList = new ArrayList<>();
        if (ObjectUtil.isEmpty(params.getSort()) || StrUtil.isBlank(params.getSort().getSidx()) || StrUtil.isBlank(params.getSort().getOrder())) {
            ParamsModel.SortParams sortParams = new ParamsModel.SortParams();
            sortParams.setSidx("date");
            sortParams.setOrder("asc");
            params.setSort(sortParams);
        }
        String sidx = params.getSort().getSidx();
        String order = params.getSort().getOrder();
        if (ObjectUtil.isNotEmpty(subAccountList)) {
            if (StrUtil.isNotBlank(sidx) && StrUtil.isNotBlank(order) && !StrUtil.equals(sidx, "date")) {
                subAccountList = subAccountList.stream().sorted(
                        new Comparator<YkfAccountInputRecordEntity>() {
                            @Override
                            public int compare(YkfAccountInputRecordEntity o1, YkfAccountInputRecordEntity o2) {
                                String value1 = StrUtil.toString(ReflectUtil.getFieldValue(o1, sidx));
                                String value2 = StrUtil.toString(ReflectUtil.getFieldValue(o2, sidx));
                                return StrUtil.equals(order, "asc") ? value1.compareTo(value2) : value2.compareTo(value1);
                            }
                        }
                ).collect(Collectors.toList());
            }
            Integer maxBeforeDays = 1;
            Integer minBeforeDays = 1;
            List<Integer> collect = subAccountList.stream().filter(o -> ObjectUtil.isNotEmpty(o.getBeforeDays())).map(YkfAccountInputRecordEntity::getBeforeDays).distinct().collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(collect)) {
                OptionalInt maxNum = collect.stream().mapToInt(Integer::intValue).max();
                OptionalInt minNum = collect.stream().mapToInt(Integer::intValue).min();
                if (maxNum.isPresent()) {
                    maxBeforeDays = maxNum.getAsInt();
                }
                if (minNum.isPresent()) {
                    minBeforeDays = minNum.getAsInt();
                }
            }
//            DateTime start = DateUtil.offsetDay(params.getCondition().getDateStart(), maxBeforeDays * -1);
//            DateTime end = DateUtil.offsetDay(params.getCondition().getDateEnd(), minBeforeDays * -1);
            Date start = params.getCondition().getDateStart();
            Date end = params.getCondition().getDateEnd();
            //查询所有满足条件的记录
            QueryWrapper<YkfAccountInputRecordEntity> queryWrapper = ParamUtils.createQueryWrapperByDefaultSort(params);
            if (StrUtil.isNotBlank(condition.getKeyword())) {
                queryWrapper.lambda().and(wrapper -> wrapper.like(YkfAccountInputRecordEntity::getAccountNo, condition.getKeyword())
                        .or().like(YkfAccountInputRecordEntity::getAccountName, condition.getKeyword())
                        .or().like(YkfAccountInputRecordEntity::getShopName, condition.getKeyword()));
            }
            queryWrapper.lambda().ge(YkfAccountInputRecordEntity::getDate, start)
                    .le(YkfAccountInputRecordEntity::getDate, end);
            List<YkfAccountInputRecordEntity> list = this.list(queryWrapper);

            //当天不检测列表
            QueryWrapper<YkfNotCheckRecordEntity> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(YkfNotCheckRecordEntity::getType, 1)
                    .ge(YkfNotCheckRecordEntity::getDate, start)
                    .le(YkfNotCheckRecordEntity::getDate, end);
            List<YkfNotCheckRecordEntity> list1 = notCheckRecordService.list(queryWrapper1);

            //永远不检测列表
            QueryWrapper<YkfNotCheckRecordEntity> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.lambda().eq(YkfNotCheckRecordEntity::getType, 2);
            List<YkfNotCheckRecordEntity> list2 = notCheckRecordService.list(queryWrapper2);
            List<String> notCheckKeyList2 = new ArrayList<>();
            if (ObjectUtil.isNotEmpty(list2)) {
                notCheckKeyList2 = list2.stream().map(o -> StrUtil.toString(o.getSubAccountId())).collect(Collectors.toList());
            }

            long l = DateUtil.betweenDay(params.getCondition().getDateStart(), params.getCondition().getDateEnd(), true) + 1;
//            if (StrUtil.equals(sidx, "date") && StrUtil.equals(order, "desc")) {
            for (int i = 0; i < l; i++) {
                Date date = condition.getDateEnd();
                if (i > 0) {
                    date = DateUtil.offsetDay(date, i * (-1));
                }
                // data就是昨日的日期
                for (YkfAccountInputRecordEntity record : subAccountList) {
                    // 这里最后查出来的是最后返回的数据
                    Integer beforeDays = (null == record.getBeforeDays() ? 1 : record.getBeforeDays());
//                    DateTime beforeDate = DateUtil.offsetDay(date, beforeDays * (-1));
                    Date beforeDate = date;

//                        String beforeDate = DateUtil.formatDate(beforeDate1);

                    // 校验爬取日期是否在子账号的有效范围内
                    if (ObjectUtil.isEmpty(record.getStartDate()) || ObjectUtil.isEmpty(record.getEndDate())
                            || record.getStartDate().compareTo(beforeDate) > 0 || record.getEndDate().compareTo(beforeDate) < 0) {
                        continue;
                    }
//                        if (beforeDate.compareTo(DateUtil.formatDate(date)) >= 0) {

                    List<String> inputKeyList = new ArrayList<>();
                    if (ObjectUtil.isNotEmpty(list)) {
                        List<YkfAccountInputRecordEntity> collect1 = list.stream().filter(o -> DateUtil.compare(o.getDate(), beforeDate) == 0).collect(Collectors.toList());
                        if (ObjectUtil.isNotEmpty(collect1)) {
                            inputKeyList = collect1.stream().map(o -> DateUtil.formatDate(o.getDate()) + o.getSubAccountId()).collect(Collectors.toList());
                        }
                    }

                    List<String> notCheckKeyList1 = new ArrayList<>();
                    if (ObjectUtil.isNotEmpty(list1)) {
                        List<YkfNotCheckRecordEntity> collect1 = list1.stream().filter(o -> DateUtil.compare(o.getDate(), beforeDate) == 0).collect(Collectors.toList());
                        if (ObjectUtil.isNotEmpty(collect1)) {
                            notCheckKeyList1 = collect1.stream().map(o -> DateUtil.formatDate(o.getDate()) + o.getSubAccountId()).collect(Collectors.toList());
                        }
                    }

                    //校验当前信息是否已录入
                    String key = DateUtil.formatDate(beforeDate) + record.getSubAccountId();
                    if (!inputKeyList.contains(key) && !notCheckKeyList1.contains(key) && !notCheckKeyList2.contains(StrUtil.toString(record.getSubAccountId()))) {
                        YkfAccountInputRecordEntity newData = new YkfAccountInputRecordEntity();
                        BeanUtil.copyProperties(record, newData);
                        newData.setDate(beforeDate);
                        resultList.add(newData);
                    }
//                        }
                }
            }
//            }
//            else {
//                for (int i = 0; i < (l + 1); i++) {
//                    Date date = condition.getDateStart();
//                    if (i > 0) {
//                        date = DateUtil.offsetDay(date, i);
//                    }
//                    for (YkfAccountInputRecordEntity record : subAccountList) {
//                        if (ObjectUtil.isEmpty(record.getStartDate()) || ObjectUtil.isEmpty(record.getEndDate()) || record.getStartDate().compareTo(date) > 0 || record.getEndDate().compareTo(date) < 0) {
//                            continue;
//                        }
//                        //校验当前信息是否已录入
//                        String key = DateUtil.formatDate(date) + record.getSubAccountId();
//                        if (!inputKeyList.contains(key)) {
//                            YkfAccountInputRecordEntity newData = new YkfAccountInputRecordEntity();
//                            BeanUtil.copyProperties(record, newData);
//                            newData.setDate(date);
//                            resultList.add(newData);
//                        }
//                    }
//                }
//            }
        }
        if (resultList.size() > 0) {
            //排序
            if (ObjectUtil.isEmpty(params.getSort()) || StrUtil.isBlank(params.getSort().getSidx()) || StrUtil.isBlank(params.getSort().getOrder())) {
                resultList = resultList.stream().sorted(Comparator.comparing(YkfAccountInputRecordEntity::getDate).reversed()).collect(Collectors.toList());
            } else {
                ParamsModel.SortParams sort = params.getSort();
                switch (sort.getSidx()) {
                    case "date":
                        if (StrUtil.equals(sort.getOrder(), "asc")) {
                            resultList = resultList.stream().sorted(Comparator.comparing(YkfAccountInputRecordEntity::getDate)).collect(Collectors.toList());
                        } else {
                            resultList = resultList.stream().sorted(Comparator.comparing(YkfAccountInputRecordEntity::getDate).reversed()).collect(Collectors.toList());
                        }
                        break;
                    case "shopName":
                        if (StrUtil.equals(sort.getOrder(), "asc")) {
                            resultList = resultList.stream().sorted(Comparator.comparing(YkfAccountInputRecordEntity::getShopName)).collect(Collectors.toList());
                        } else {
                            resultList = resultList.stream().sorted(Comparator.comparing(YkfAccountInputRecordEntity::getShopName).reversed()).collect(Collectors.toList());
                        }
                        break;
                    case "accountName":
                        if (StrUtil.equals(sort.getOrder(), "asc")) {
                            resultList = resultList.stream().sorted(Comparator.comparing(YkfAccountInputRecordEntity::getAccountName)).collect(Collectors.toList());
                        } else {
                            resultList = resultList.stream().sorted(Comparator.comparing(YkfAccountInputRecordEntity::getAccountName).reversed()).collect(Collectors.toList());
                        }
                        break;
                }
            }
            //结果分页
            IPage<YkfAccountInputRecordEntity> page = new Query<YkfAccountInputRecordEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
            int totalcount = resultList.size();
            Long size = params.getPage().getSize();
            Long current = params.getPage().getIndex();
            page.setTotal(totalcount);
            long pagecount = 0;
            long m = totalcount % size;
            if (m > 0) {
                pagecount = totalcount / size + 1;
            } else {
                pagecount = totalcount / size;
            }
            page.setPages(pagecount);

            if (m == 0) {
                resultList = resultList.subList((int) ((current - 1) * size), (int) (size * (current)));
            } else {
                if (current == pagecount) {
                    resultList = resultList.subList((int) ((current - 1) * size), (int) totalcount);
                } else {
                    resultList = resultList.subList((int) ((current - 1) * size), (int) (size * (current)));
                }
            }
            page.setRecords(resultList);
            page.setSize(size);
            page.setCurrent(current);
            return new PageUtils(page);
        } else {
            IPage iPage = new Page();
            iPage.setTotal(0);
            iPage.setPages(0);
            iPage.setRecords(new ArrayList());
            return new PageUtils(iPage);
        }
    }

    public List<YkfAccountInputRecordEntity> toBeEnteredList(ExcelReq req) {
        List<YkfAccountInputRecordEntity> resultList = new ArrayList<>();
        if (ObjectUtil.isEmpty(req) || StrUtil.isBlank(req.getDateStart()) || StrUtil.isBlank(req.getDateEnd())) {
            return resultList;
        }
//        DateTime endDate = DateUtil.date();
//        DateTime startDate = DateUtil.offsetDay(endDate, -30);
        Date startDate = DateUtil.parse(req.getDateStart(), "yyyy-MM-dd");
        Date endDate = DateUtil.parse(req.getDateEnd(), "yyyy-MM-dd");
        //查询所有满足条件的子账号
        List<YkfAccountInputRecordEntity> subAccountList = baseMapper.getSubAccountList(new YkfAccountInputRecordEntity());
        if (ObjectUtil.isNotEmpty(subAccountList)) {

            //查询所有满足条件的记录
            List<YkfAccountInputRecordEntity> list = this.list();
            List<String> inputKeyList = new ArrayList<>();
            if (ObjectUtil.isNotEmpty(list)) {
                inputKeyList = list.stream().map(o -> DateUtil.formatDate(o.getDate()) + o.getSubAccountId()).collect(Collectors.toList());
            }
            //当天不检测列表
            QueryWrapper<YkfNotCheckRecordEntity> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(YkfNotCheckRecordEntity::getType, 1)
                    .ge(YkfNotCheckRecordEntity::getDate, startDate)
                    .le(YkfNotCheckRecordEntity::getDate, endDate);

            List<String> notCheckKeyList1 = new ArrayList<>();
            List<YkfNotCheckRecordEntity> list1 = notCheckRecordService.list(queryWrapper1);
            if (ObjectUtil.isNotEmpty(list1)) {
                notCheckKeyList1 = list1.stream().map(o -> DateUtil.formatDate(o.getDate()) + o.getSubAccountId()).collect(Collectors.toList());
            }
            //永远不检测列表
            QueryWrapper<YkfNotCheckRecordEntity> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.lambda().eq(YkfNotCheckRecordEntity::getType, 2);
            List<YkfNotCheckRecordEntity> list2 = notCheckRecordService.list(queryWrapper2);
            List<String> notCheckKeyList2 = new ArrayList<>();
            if (ObjectUtil.isNotEmpty(list2)) {
                notCheckKeyList2 = list2.stream().map(o -> StrUtil.toString(o.getSubAccountId())).collect(Collectors.toList());
            }
            long l = DateUtil.betweenDay(startDate, endDate, true) + 1;
            for (int i = 0; i < (l + 1); i++) {
                Date date = startDate;
                if (i > 0) {
                    date = DateUtil.offsetDay(date, i);
                }
                for (YkfAccountInputRecordEntity record : subAccountList) {
                    if (ObjectUtil.isEmpty(record.getDateStart()) || ObjectUtil.isEmpty(record.getDateEnd()) || record.getDateStart().compareTo(date) > 0 || record.getDateEnd().compareTo(date) < 0) {
                        continue;
                    }
                    //校验当前信息是否已录入
                    String key = DateUtil.formatDate(date) + record.getSubAccountId();
                    if (!inputKeyList.contains(key)) {
                        YkfAccountInputRecordEntity newData = new YkfAccountInputRecordEntity();
                        BeanUtil.copyProperties(record, newData);
                        newData.setDate(date);
                        resultList.add(newData);
                    }
                }
            }
        }
        return resultList;
    }

//    public static void main(String[] args) {
//        long l = DateUtil.betweenDay(DateUtil.date(), DateUtil.date(), false);
//        System.out.println();
//    }
}
